Read an entire file into memory in Go using the os.ReadFile function with a single line of code.
Use os.ReadFile to load the entire file contents into a byte slice in a single call.
package main
import (
"fmt"
"os"
)
func main() {
data, err := os.ReadFile("/home/sd/crewai/src/go/go/README.md")
if err != nil {
fmt.Println("Error reading file:", err)
return
}
fmt.Println(string(data))
}
os.ReadFile grabs the whole file at once and puts it into your program's memory. It is the fastest and easiest way to read small to medium-sized files. Think of it like photocopying an entire document onto a single sheet of paper instead of reading it page by page.