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
Release: 2024-12-21 11:39:11
Original
680 people have browsed it

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
}
Copy after login

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)
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template