Writing the file
Writing a file is an essential task for every programmer; Go supports multiple ways on how you can do this. This recipe will show a few of them.
How to do it...
- Open the console and create the folder
chapter06/recipe03
. - Navigate to the directory.
- Create the
writefile.go
file with the following content:
package main import ( "io" "os" "strings" ) func main() { f, err := os.Create("sample.file") if err != nil { panic(err) } defer f.Close() _, err = f.WriteString("Go is awesome!\n") if err != nil { panic(err) } _, err = io.Copy(f, strings.NewReader("Yeah! Go is great.\n")) if err != nil { panic(err) } }
- Execute the code by running
go run writefile.go
in the main Terminal. - Check the content of the created
sample.file
:

How it works...
The os.File
type...