black hat book go/ variable not used in golang

Asked

Viewed 68 times

-1

func foo(i interface{}) {
switch v := i.(type) {
case int:
fmt.Println("I'm an integer!")
case string:
fmt.Println("I'm a string!")
default:
fmt.Println("Unknown type!")
}
}

I researched this control structure, but as this language is new I don’t find much in our language, my understanding of English is not the best. I took from the book "black hat go" and this code is not working, could anyone tell me why? and how to make it work?

compiler logs(1.13):

# command-line-arguments
./hw.go:6:9: v declared and not used

1 answer

3

That’s exactly what the mistake says.

While some languages show an alert when you declare a variable but don’t use it, Go gives you a build error. This is a feature of the language that has already been questioned, but the creators are quite resilient to this decision, and it seems that nothing will change for now.

There is also no way to pass a parameter to the compiler to turn off this variable analysis, so the way is to fix the code and remove unused variables:

func foo(i interface{}) {
  switch i.(type) {
  case int:
    fmt.Println("I'm an integer!")
  case string:
    fmt.Println("I'm a string!")
  default:
    fmt.Println("Unknown type!")
  }
}

Another strategy that may be useful while debugging the program is to assign the value of an unused variable to _. This symbol basically discards any value assigned to it, and the compiler does not complain when you are being explicit about a value that is not being used.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.