I've stumbled across a strange issue where the code below fails to compile:
func main() {
var val reflect.Value
var tm time.Time
if tm, err := time.Parse(time.RFC3339, "2018-09-11T17:50:54.247Z"); err != nil {
panic(err)
}
val = reflect.ValueOf(tm)
fmt.Println(val, tm, reflect.TypeOf(tm))
}
with the error (the code is what linter recommends).:
$ go run main.go
# command-line-arguments
./main.go:13:5: tm declared and not used
Note the tm
variable is indeed used.
If however I add an else block - everything compiles as expected:
func main() {
var val reflect.Value
var tm time.Time
if tm, err := time.Parse(time.RFC3339, "2018-09-11T17:50:54.247Z"); err != nil {
panic(err)
} else {
val = reflect.ValueOf(tm)
}
fmt.Println(val, tm, reflect.TypeOf(tm))
}
This looks like a bug in the compiler or perhaps a known issue? Any idea? (I'm using go 1.11)
edit: to all respondends so far. As per: https://golang.org/ref/spec#Short_variable_declarations
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.
if
opens a new nested block, so this doesn't apply (see my answer for a more detailed explanation). – Leo K