Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: error variable reassigning, proper use?

Tags:

go

I'm confusing about the reassignment of the err variable for errors in Go.

For example, I tend to be doing this:

err1 := Something()
checkErr(err1)
str, err2 := SomethingElse()
checkErr(err2)
err3 := SomethingAgain()
checkErr(err3)

But I'm always losing track of this and have millions of useless err variables floating around that I don't need, and it makes the code messy and confusing.

But then if I do this:

err := Something()
checkErr(err)
str, err := SomethingElse()
checkErr(err)
err := SomethingAgain()
checkErr(err)

...it gets angry and says err is already assigned.

But if I do this:

var err error
err = Something()
checkErr(err)
str, err = SomethingElse()
checkErr(err)
err = SomethingAgain()
checkErr(err)

...it doesn't work because str needs to be assigned with :=

Am I missing something?

like image 964
Alasdair Avatar asked Oct 24 '25 16:10

Alasdair


1 Answers

you're almost there... at the left side of := there needs to be at least one newly create variable. But if you don't declare err in advance, the compiler tries to create it on each instance of :=, which is why you get the first error. so this would work, for example:

package main

import "fmt"

func foo() (string, error) {
 return "Bar", nil
}

func main() {
   var err error

   s1, err := foo()
   s2, err := foo()

   fmt.Println(s1,s2,err)
}

or in your case:

//we declare it first
var err error

//this is a normal assignment
err = Something()
checkErr(err)

// here, the compiler knows that only str is a newly declared variable  
str, err := SomethingElse()
checkErr(err)

// and again...
err = SomethingAgain()
checkErr(err)
like image 64
Not_a_Golfer Avatar answered Oct 26 '25 07:10

Not_a_Golfer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!