Variable definition is not defined

Issue

I’ve searched Google and saw some samples, but it’s just not clicking. I’m new to Go, so I hope someone can clarify this for me. I have the following code:

var configFile string
var keyLength int
var outKey string
var outconfig string

for index, item := range args {

    if strings.ToLower(item) == "-config" {
        configFile = args[index + 1]
    }else if strings.ToLower(item) == "-keylength" {
        keyLength, _ = strconv.Atoi(args[index + 1])
    }else if strings.ToLower(item) == "-outkey" {
        outKey = args[index + 1]
    }else if strings.ToLower(item) == "-outconfig" {
        outconfig = args[index + 1]
    }        
}   

But I’m getting an error for all the variables where it’s being defined with the following error "configFile declared but not used". If I can get some advice to help me better understand this problem

Solution

You assign values to the variables, but never use them after. That’s why Go throws an error.

See this example:

package main

func f() {
    var unassignedVar string
    var unusedVar = "I am not read"
    var usedVar = "I am read"

    print(usedVar)
}

For the first two variables, Go will throw an error: unassignedVar is not even assigned a value, unusedVar is assigned a value but not used afterwards. usedVar is both assigned a value and used later on.

See the example on the Go Playground.

Answered By – fjc

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.