0

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

adviner
  • 3,295
  • 10
  • 35
  • 64
  • The variables need to be *used* for the program to compile. Assigning to declared variables is not considered "effective usage", i.e. assigning to a declared variable that's not read by any other piece of code in the program has no effect on the program's output. In other words, the compiler considers those variables as useless and they should therefore be removed from the source. – mkopriva Nov 17 '22 at 08:01
  • 1
    oh, I get it. Thanks for clearing it up for me. After adding code to use the variables the errors went away. – adviner Nov 17 '22 at 08:02

1 Answers1

0

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.

fjc
  • 5,590
  • 17
  • 36