I cannot find the answer anywhere, so this is the situation:
// err has not yet been declared here
globalVar := "string"
if globalVar == "string" {
globalVar, err := doSomethingWithString()
if err != nil {
// error handling
}
}
That second globalVar
declaration gives an error both then :=
and when '=' is used:
- With
:=
it saysglobalVar declared and not used
because now globalVar is a new variable in the inner scope. - With
=
it saysundefined err
because it has not yet been declared.
So basically, there should be a way to define the difference between =
and :=
for each variable on the left side of the declaration.
I see two possible solutions, which are both equally ugly in my opinion:
// err has not yet been declared here
globalVar := "string"
if globalVar == "string" {
globalVar2, err := doSomethingWithString()
if err != nil {
// error handling
}
globalVar = globalVar2
}
or
globalVar := "string"
var err error
if globalVar == "string" {
globalVar, err = doSomethingWithString()
if err != nil {
// error handling
}
}
Do I have to use one of these work-arounds or is there a correct way of achieving what I need?
The second solution seems the least ugly, but if there are many variables you only need in the if-scope, these variables will not be removed after the scope and persist the whole outer scope. So the fist solution seems the best in my opinion.
But I'd like to hear how others resolve this situation...