In this example, we will show you how to read a file into a string in Go with an example.
The ioutil.ReafFile function reads the whole file into a string. This function is convenient but should not be used with very large files.
Go - read the file into a string
The example reads the whole file and prints it to the console.
Let's create a 'sample.txt' file and add the following content to it:
My first fav programming languge is Go Lang My second fav programming languge is Java My third fav programming languge is Python
Let's create a file named go_example.go and add the following content to it:
package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
content, err := ioutil.ReadFile("sample.txt")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(content))
}
Output:
G:\GoLang\examples>go run go_example.go My first fav programming languge is Go Lang My second fav programming languge is Java My third fav programming languge is Python