为什么在GO init()方法中出现错误?

So I understand that in go, init() is a special method that can be used to initialize an object in a package. When I try to use this technique, I get an error that the variable is declared and not used. For example:

package fizzbuzz

var foo string

func init() {
    foo := "bar"
}

It seems to me that most of the time variables that you put in this method will not be used local to int(), so that is just fine. What am I missing?

That just creates a local variable named "foo" inside the method. You need to assign the string to the already declared var at the module scope via foo = "bar".

In Go foo:="bar" is a short assignment statement that can be used in a function in place of a var declaration.

So essentially what you have done is declare a new foo variable inside the init method instead of used the global foo

The keyword := is shorthand for "assign to new variable"-- Go lets you shadow old variables with new variables in deeper scopes.

foo exists within the global scope, but you've created a new foo inside the init() scope-- therefore, inside of init(), foo shadows the global foo.

Furthermore, Go complains about unused variables in local scopes. In this case, your foo in init() is unused.

So, to walk over this,

  • You defined foo in the global scope
  • You entered init(), and then defined a foo within init(), shadowing the global foo
  • You did not use the local variable foo.

If you want to set the global foo, use =, not :=, as := creates a new variable.