Home > Software design >  The go-compiler reports variable declared but not used when using pointers
The go-compiler reports variable declared but not used when using pointers

Time:02-04

I have a snippet of code that i am unable to understand why the go compiler is reporting that a variable is declared but not used:

package main
import "fmt"
func main() {
    var StringSlice []*string
    
    MyStr0 := "Zero"
    StringSlice = append(StringSlice, &MyStr0)
    MyStr1 := "One"
    StringSlice = append(StringSlice, &MyStr1)
    MyStr2 := "Two"
    StringSlice = append(StringSlice, &MyStr2)

    var StrPtr *string
    for i, Value := range StringSlice {
        fmt.Println(Value)
        if i == 1 {
            StrPtr = Value
        }
    } // END for

With the Printf statement commented out, the go compiler claims »./prog.go:15:6: StrPtr declared but not used« - see the example in the go-playground at: https://go.dev/play/p/J3p4NDR6fBm When the Printf is commented out, everything is fine and there's even the correct string-pointer stored in StrPtr… Thank you very much in advance for your help!

CodePudding user response:

The problem is that you are not using StrPtr. You are reassigning it, but it is never read. If you add that to a Printf statement the error will go away.

package main
import "fmt"
func main() {
    var StringSlice []*string

    MyStr0 := "Zero"
    StringSlice = append(StringSlice, &MyStr0)
    MyStr1 := "One"
    StringSlice = append(StringSlice, &MyStr1)
    MyStr2 := "Two"
    StringSlice = append(StringSlice, &MyStr2)

    var StrPtr *string
    for i, Value := range StringSlice {
        fmt.Println(Value)
        if i == 1 {
            StrPtr = Value
            fmt.Println(StrPtr) // <--- add this
        }
    } // END for
}
  •  Tags:  
  • go
  • Related