-4

My intuitive approach: https://play.golang.org/p/6xzg7TK1IH

and it doesn't work.

Can you share some alternative ways?

user1937358
  • 239
  • 1
  • 2
  • 8
  • if variable not needed use underscore https://play.golang.org/p/S9kzv_dBlk – pkuderov Jan 13 '16 at 11:57
  • 5
    duplicate for http://stackoverflow.com/questions/21743841/how-to-avoid-annoying-error-declared-and-not-used-from-golang. There's a nice explanation of why go language creators added this check. – pkuderov Jan 13 '16 at 12:03

2 Answers2

2

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)
}
Endre Simo
  • 11,330
  • 2
  • 40
  • 49
1

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)
    }
}
topskip
  • 16,207
  • 15
  • 67
  • 99