How to declare single variable for "IF/Else" statement


(Javier Salas) #1

Hello

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:

query, err := "test", errors.Errorf("IF statement error")
fmt.Print(query, err)

But if I do this, I got an error that are unused variables and unresolved reference:

if (tablename == "test"){
   query, err := "test", errors.Errorf("IF statement error")
} else {
   query, err := "anothertest", errors.Errorf("Else statement Error")
}

fmt.Print(query, err)

Any idea how could I solve that?


(Petko Petkov) #2
package main

import (
	"fmt"
)

var (
	query  string
	err error
)	

func main() {
 	
	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)
}

https://play.golang.org/p/Ao8yZP3vmGW


(Ignacio Gómez) #3

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"

(Javier Salas) #4

awesome!!! that is the correct answer! that helped me on what I tried to do.