i’m running into an issue trying to declare variables and use it with if/else statement, I’m new in go and just want to create something for fun, here is my issue, if I do this, everything works well:
Please note that the given example declares global variables query and err. You may keep them local to the main function simply changing it to this:
package main
import (
"fmt"
)
func main() {
var query string
var err error
tablename := "foobar"
if (tablename == "test"){
err, query = fmt.Errorf("IF statement error"),"test"
} else {
err, query = fmt.Errorf("Else statement error"),"anothertest"
}
fmt.Printf("My query is: %s and error is: %s", query, err)
}
Why is this relevant? Because when you declared query and error inside the if/else, they were local to that scope, and so not visible at the function scope. A typical example of this is when you have some error and then in the eror check you redeclare and shadow the error:
err := errors.New("outer error")
if err != nil {
err := someErroringFunc()
//Now err refers to the latest error and is shadowing the outer err.
fmt.Println(err) //This prints the error from someErrorFunc().
}
fmt.println(err) // This prints "outer error"