My intuitive approach: https://play.golang.org/p/6xzg7TK1IH
and it doesn't work.
Can you share some alternative ways?
My intuitive approach: https://play.golang.org/p/6xzg7TK1IH
and it doesn't work.
Can you share some alternative ways?
You are declaring a variable (moreline
) which you don't use it. You have two options here: either to replace the moreline
with underscore, which means you can omit the return value.
for moreline {
line, _, err := bio.ReadLine()
if err != nil {
log.Fatal(err)
}
fmt.Println(line)
}
But a better option will be to use the ReadScanner
, ReadBytes('\n')
or ReadString('\n')
.
Checking the bufio.go
file this is what you get as description for the ReadLine
method:
ReadLine is a low-level line-reading primitive. Most callers should use ReadBytes('\n') or ReadString('\n') instead or use a Scanner.
Calling UnreadByte
after ReadLine
will always unread the last byte read (possibly a character belonging to the line end) even if that byte is not part of the line returned by ReadLine
. ReadLine
either returns a non-nil line or it returns an error, never both.
So this would be a better option:
scanner := bufio.NewScanner(bio)
for scanner.Scan() {
line := scanner.Text()
fmt.Printf("%v\n", line)
}
You use :=
which discards the previous contents of the variables. You don't use morelines
in that scope, thus the error message.
If you declare your variables beforehand and don't use :=
, it works fine. The function ReadLine()
might not do what you think it should do.
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
bio := bufio.NewReader(os.Stdin)
var line []byte
var err error
moreline := true
for moreline {
line, moreline, err = bio.ReadLine()
if err != nil {
log.Fatal(err)
}
fmt.Println(line)
}
}