Short variable declaration and “variable declared and not used” error

前端 未结 2 1158
离开以前
离开以前 2021-01-23 08:18

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         


        
2条回答
  •  情话喂你
    2021-01-23 09:05

    Your if statement declares a new variable tm that exists only within the scope of the if block and is indeed never used:

    if tm, err := time.Parse(time.RFC3339, "2018-09-11T17:50:54.247Z"); err != nil {
        panic(err)
    }
    

    In Go, := declares a new variable and initializes it. You probably meant:

    func main() {
        var val reflect.Value
        var tm time.Time
        var err error
    
        // Note the change to normal assignment here instead of :=
        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))
    }
    

    The := shortcut operator is demonstrated in the Tour of Go and explained in the Go spec, the latter of which includes:

    It is shorthand for a regular variable declaration with initializer expressions but no types:

    "var" IdentifierList = ExpressionList .

    Scoping is explained in the Go spec as well.

提交回复
热议问题