January 2018
Intermediate to advanced
340 pages
8h 6m
English
You can write using just the os package, which is needed already to open the file. Since all Go executables are statically linked binaries, every package you import increases the size of your executable. Other packages such as io, ioutil, and bufio provide some more help, but they are not necessary:
package main
import (
"log"
"os"
)
func main() {
// Open a new file for writing only
file, err := os.OpenFile(
"test.txt",
os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
0666,
)
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Write bytes to file
byteSlice := []byte("Bytes!\n")
bytesWritten, err := file.Write(byteSlice)
if err != nil {
log.Fatal(err)
}
log.Printf("Wrote %d bytes.\n", bytesWritten)
}
Read now
Unlock full access