When working with input/output operations in Go, it's often necessary to read a line of text as a string. However, the standard library readline functions primarily return byte arrays.
The Readln function provides a convenient way to convert a byte array from readline to a string. Here's how it works:
<br>import (</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">"bufio" "fmt" "os"
)
// Readln returns a single line (without the ending n)
// from the input buffered reader.
// An error is returned iff there is an error with the
// buffered reader.
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("filename.txt")
if err != nil {
fmt.Println("error opening file= ", err) os.Exit(1)
}
r := bufio.NewReader(f)
for line, err := Readln(r); err == nil; line, err = Readln(r) {
fmt.Println(line)
}
if err != io.EOF {
fmt.Println("error reading file= ", err) os.Exit(1)
}
}
The main() function opens a file, creates a buffered reader from it, and then uses the Readln function to iterate over each line in the file. The Readln function returns both the line as a string and an error value. The program continues reading lines until the end of the file is reached or an error occurs.
This approach simplifies line reading in Go, providing a more idiomatic and user-friendly method to obtain strings from input.
The above is the detailed content of How Can Go's `Readln` Function Simplify Idiomatic Line Reading?. For more information, please follow other related articles on the PHP Chinese website!