13

I am a newbee to golang, and I write a program to test io package:

func main() {
    readers := []io.Reader{
         strings.NewReader("from string reader"),
         bytes.NewBufferString("from bytes reader"),
    }

    reader := io.MultiReader(readers...)
    data := make([]byte, 1024)

    var err error
    //var n int

    for err != io.EOF {
        n, err := reader.Read(data)
        fmt.Printf("%s\n", data[:n])
    }
    os.Exit(0)
}

The compile error is "err declared and not used". But I think I have used err in for statement. Why does the compiler outputs this error?

1
  • You could also remove almost all of that code by just using n, err := io.Copy(os.Stdout, io.MultiReader(readers...) (and the os.Exit(0) at the end is unnecessary) Commented Jan 18, 2014 at 20:01

1 Answer 1

28

The err inside the for is shadowing the err outside the for, and it's not being used (the one inside the for). This happens because you are using the short variable declaration (with the := operator) which declares a new err variable that shadows the one declared outside the for.

Sign up to request clarification or add additional context in comments.

3 Comments

I was under the impression that the := short declaration operator, when used on multiple values, let you use some of them for pre-declared variables as long as at least one was being newly declared. Why in this case doesn't it reuse the err declared earlier if that's the case?
@thomasrutter because those declarations are in different blocks
Thanks, I seem to have to frequently make another var declaration above a call instead of using short declaration := in order to assign to both an error and a variable in a parent block.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.