This is a better example: https://go.dev/play/p/MRvbZLGB2Bi If you now change the function signature to return (int32, error), then it will complain about a type mismatch.
On Wed, Jan 14, 2026, 14:36 'Brian Candler' via golang-nuts < [email protected]> wrote: > I'm having trouble understanding something in the go spec for short > variable (re)declarations. The spec says: > > "redeclaration can only appear in a multi-variable short declaration. > *Redeclaration > does not introduce a new variable; it just assigns a new value to the > original.*" > > It's that last sentence that I'm having problems squaring with observed > behaviour. > > Example 1: https://go.dev/play/p/M43ilvI-hB9 > > package main > > import "fmt" > > func myfunc() (int, error) { > return 123, nil > } > > func main() { > var code int > if code, err := myfunc(); err != nil { // line 11 > fmt.Printf("Error: %s", err) > return > } > fmt.Printf("code is %d", code) > } > > This gives a compile error: > > ./prog.go:11:5: declared and not used: code > > Adding a line to workaround this gives Example 2: > https://go.dev/play/p/TVfTCc2bjAO > > func main() { > var code int > if code, err := myfunc(); err != nil { > fmt.Printf("Error: %s", err) > > * _ = code* return > } > fmt.Printf("code is %d", code) > } > > This prints 0, not 123. > > These examples seem to show that the variable "code" (re)declared in the > if-statement is a completely new variable which is local to the if block > only. > > (Aside: what I was actually trying to achieve is to tidy some program > logic so that the "err" variable is local to the block - and hence can't > accidentally be bound to later on in the function - whilst making the > "code" value persist beyond the block where it can be used later) > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to [email protected]. > To view this discussion visit > https://groups.google.com/d/msgid/golang-nuts/37978205-dafe-40e3-bf6d-f3f55aff7463n%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/37978205-dafe-40e3-bf6d-f3f55aff7463n%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion visit https://groups.google.com/d/msgid/golang-nuts/CADgY6e_ACW-PcRKKshW7_dGoeatNY5fAY8n5O8KvmLuF%2BXgSLA%40mail.gmail.com.
