-3

I have the following Go example:

package main

import (
    "fmt"
    "log"
    "os"
    "strconv"
)

func main() {
    numberOfUsers := 10
    numberOfUsersStr, found := os.LookupEnv("NUMBER_OF_USERS")
    if found {
        numberOfUsers, err := strconv.Atoi(numberOfUsersStr)
        if err != nil {
            log.Fatalln(err)
        }
    }
    fmt.Printf("Number of users: %d", numberOfUsers)
}

When building this snipper, I get the following error:

> go build -o app .
.\app.go:14:3: numberOfUsers declared but not used

Clearly the variable is used in the last print statement, however it seems hidden from the compiler. What am I missing?

2 Answers2

1

When using :=, you're declaring a new variable. That means the numberOfUsers here:

numberOfUsers, err := strconv.Atoi(numberOfUsersStr)

is actually shadowing your other numberOfUsers variable.

You can fix it by declaring err beforehand and then using just = instead of := so that you are only assigning a new value to the variable and not declaring a new variable.

var err error
numberOfUsers, err = strconv.Atoi(numberOfUsersStr)
Gavin
  • 4,365
  • 1
  • 18
  • 27
0

The numberOfUsers variable in this line is unused: numberOfUsers, err := strconv.Atoi(numberOfUsersStr).

Here you are redeclaring a new variable numberOfUsers in the scope of the if statement. This variable is not used in that scope, hence the error.

You probably want something like this:

func main() {
    numberOfUsers := 10
    numberOfUsersStr, found := os.LookupEnv("NUMBER_OF_USERS")
    if found {
        var err error
        numberOfUsers, err = strconv.Atoi(numberOfUsersStr)
        if err != nil {
            log.Fatalln(err)
        }
    }
    fmt.Printf("Number of users: %d", numberOfUsers)
}

Notice the difference between := (declare an assign a new variable) and = (only assign).

norbjd
  • 10,166
  • 4
  • 45
  • 80
  • I see. But isn't the scope inherited inside the if block? – Goplayer Aug 15 '22 at 14:19
  • The variable `numberOfUsers` indeed exists in the `if` block, but here, you are recreating a variable with the same name inside that `if` block (shadowing) because of the `:=`. – norbjd Aug 15 '22 at 14:23
  • But why the error message isn't something like "no new variables on left side of :=" ? – Goplayer Aug 15 '22 at 14:24
  • Well, there is a new variable on left side (`err`). Anyway, even without this `err`, you'd get the same error. You can always redefine variables even if they already exist. Shadowing is allowed, so an error like "no new variables on left side of :=" would not make sense I guess. – norbjd Aug 15 '22 at 14:29