How to read an entire file into a string variable in Go
Hello everyone! I just started learning Go and encountered a seemingly simple task — reading the contents of a text file into a string variable. In other languages (e.g., Python), this is done in one line, but in Go I got confused.
I have a file `data.txt` that is located next to the executable file. I want to get its contents as a `string`. Here's what I tried:
```go
package main
import (
"fmt"
"os"
)
func main() {
file, err := os.Open("data.txt")
if err != nil {
fmt.Println(err)
return
}
// What next? How to read all the contents?
}
```
I see that `os.Open` returns `*os.File`, but I don't understand how to get a string from it. I tried reading byte by byte via `file.Read(buf)`, but you need to know the buffer size in advance.
No answers yet.
Log in to leave an answer