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:
:=
it says globalVar declared and not used
because now globalVar is a new variable in the inner scope.=
it says undefined 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...
In Go language variables are created in two different ways: Using var keyword: In Go language, variables are created using var keyword of a particular type, connected with name and provide its initial value. Important Points: In the above syntax, either type or = expression can be omitted, but not both.
Declaring multiple variables in a single declaration could cause confusion about the types of variables and their initial values.
Local variables exist within functions. Here we use var g = "global" to create a global variable outside of the function. Then we define the function printLocal() . Inside of the function a local variable called l is assigned and then printed out.
Just don't use := in this case and predeclare both globalVar and err.
var (
globalVar string
err error
)
globalVar = "string"
if globalVar == "string" {
globalVar, err = doSomethingWithString()
if err != nil {
// error handling
}
}
or alternatively if you want to limit the scope of err:
globalVar := "string"
if globalVar == "string" {
var err error
globalVar, err = doSomethingWithString()
if err != nil {
// error handling
}
}
http://play.golang.org/p/73bF_tHYsC for an example similar to the previous answer.
:= is meant as a convenience when you want to declare and assign in one statement. If it's getting in the way just don't use it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With