This code:
package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, playground")
var a bool
var b interface{}
b = true
if a, ok := b.(bool); !ok {
fmt.Println("Problem!")
}
}
Yields this error in the golang playground:
tmp/sandbox791966413/main.go:11:10: a declared and not used
tmp/sandbox791966413/main.go:14:21: a declared and not used
This is confusing because of what we read in the short variable declaration golang docs:
Unlike regular variable declarations, a short variable declaration may redeclare variables provided they were originally declared earlier in the same block (or the parameter lists if the block is the function body) with the same type, and at least one of the non-blank variables is new. As a consequence, 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.
So, my questions:
- Why can't I redeclare the variable in the code snippet above?
Supposing I really can't, what I'd really like to do is find a way to populate variables with the output of functions while checking the error in a more concise way. So is there any way to improve on the following form for getting a value out of an error-able function?
var A RealType if newA, err := SomeFunc(); err != nil { return err } else { A = newA }