Home >Backend Development >Golang >How Can I Efficiently Read a Line into a String in Go?

How Can I Efficiently Read a Line into a String in Go?

DDD
DDDOriginal
2024-12-21 11:39:11682browse

How Can I Efficiently Read a Line into a String in Go?

Efficiently Reading a Line to String in Go

The Go standard library provides low-level functions for reading input, returning byte arrays instead of strings. For ease of use, we explore an alternative approach to obtaining a string directly from a readline function.

Custom Readln Function

To simplify readline operations, we create a custom Readln function that reads a single line (excluding the newline character) from a provided bufio.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
}

Example Usage

Using the Readln function, we can read lines from a file and print them to stdout:

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 approach avoids the need to manually convert byte arrays to strings, streamlining the process of obtaining strings from readline functions in Go.

The above is the detailed content of How Can I Efficiently Read a Line into a String in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn