Bobby
Bobby

Reputation: 18305

Why is variable declaration not allowed here?

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
}

Upvotes: 1

Views: 1345

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109357

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.

Upvotes: 3

Related Questions