os.ReadFile reads an entire named file into a []byte and returns a possible error. It is the simplest choice when the complete file contents are needed. section 7.1.1
Account for these trade-offs when choosing the whole-file approach:
- Convert the returned bytes to a string when writing textual contents to standard output. section 7.1.1
- Check the returned error before using the data; handle ErrUnexpectedEOF separately when that condition matters. section 7.1.1
- Expect memory use to grow with the file because ReadFile preallocates byte-slice space, even when accessing the first byte fails. section 7.1.1
- Prefer os.Open with sequential or chunked processing for very large or streamable files. section 7.1.1
Output a file
Read myfile.txt, panic on failure, and log the complete contents after converting the byte slice to a string. section 7.1.1
Listing 7.1 Outputting contents of a file
package main
import (
"log"
"os"
)
func main() {
data, err := os.ReadFile("myfile.txt") #1
if err != nil {
panic(err)
}
log.Println(string(data)) #2
}
Runnable Go listing demonstrating the call, error check, byte-to-string conversion, and output. section 7.1.1

