1

Why does testC() fail to compile in the following go code? I would expect that the behavior would match that of testB() with the exception that err's scope would be limited to the if block.

The error message provided by the compiler is resp declared and not used

package main

import "fmt"

func main() {
    testA()
    testB()
    testC()
    testD()
}

// valid
func testA() {
    resp, err := generateInt()
    fmt.Println(fmt.Sprintf("Resp=%v Error=%v", resp, err))
}

// valid
func testB() {
    var resp *int
    resp, err := generateInt()
    fmt.Println(fmt.Sprintf("Resp=%v Error=%v", resp, err))
}

// does not compile
func testC() {
    var resp *int
    if resp, err := generateInt(); err != nil {
        fmt.Println("error=%v", err)
        return
    }
    fmt.Println("Resp=%d", *resp)
}

// valid
func testD() {
    var resp *int
    var err error
    if resp, err = generateInt(); err != nil {
        fmt.Println("error=%v", err)
        return
    }
    fmt.Println("Resp=%d", *resp)
}

func generateInt() (*int, error) {
    result := 5
    return &result, nil
}
1
  • this is because you are not using an internal variable,right? Commented Sep 22, 2015 at 20:05

1 Answer 1

3

In this example:

var resp *int
if resp, err := generateInt(); err != nil {

The short variable declaration is redeclaring the resp variable. Because an if's statement is scoped to the inside the if block, it only shadows the first resp variable within that block, leaving the first unused.

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

Comments

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.