How to disable errors when variable not used?


(cinematik) #1

How to disable errors when variable declared but not used? Is it possible?


(Lutz Horn) #2

No. And you should not do this. If your code has errors, fix them.


(BB-8) #3

@lutzhorn Is correct, you should probably try to not ignore errors in your codebase.

However, the answer to your question is to substitute the variable name with an underscore. For example, if you were iterating over a slice you might want to ignore the slice index passed from range.

numbers := []int{43, 21, 33, 49, 58, 36, 17, 78}

for index, number := range numbers {
    fmt.Printf("Number: %d (Index %d)\n", number, index) // Number 43 (Index 0)
}

Could become:

numbers := []int{43, 21, 33, 49, 58, 36, 17, 78}

for _, number := range numbers {
    fmt.Printf("Number: %d", number) // Number 43
}

I hope this was helpful.