In Go, the standard library provides low-level raw functions for readline operations, which return byte arrays. Is there a more convenient method to obtain a string from a readline function?
Idiomatic Solution
The idiomatic approach to readline to string in Go is to utilize the bufio.Reader struct. The Readln() function returns a line (without the trailing newline n) from the input buffered reader.
import ( "bufio" "fmt" "os" ) func readln(r *bufio.Reader) (string, error) { var ( isPrefix bool = true err error = nil line, ln []byte ) for isPrefix && err == nil { line, isPrefix, err = r.ReadLine() ln = append(ln, line...) } return string(ln), err } func main() { f, err := os.Open(fi) if err != nil { fmt.Println("error opening file= ", err) os.Exit(1) } r := bufio.NewReader(f) s, e := readln(r) for e == nil { fmt.Println(s) s, e = readln(r) } }
This function reads lines from a file, stripping the newline character (n) and printing each line to the console.
The above is the detailed content of How to Efficiently Read a Line from a File as a String in Go?. For more information, please follow other related articles on the PHP Chinese website!