Go语言错误处理问题/误解? [关闭]

Ok so I am using the following code,

err := r.ParseForm()
if err != nil {
    log.Panic(err)
}

var user User

err := decoder.Decode(&user, r.PostForm)
if err != nil {
    log.Panic(err)
}

Now when I try to run this code, I get the following error,

no new variables on left side of :=

Now I know that this is due to using the same variable, in this case err but I have seen lots of examples where this is how other developers deal with error handling?

The way that I have been using is just to use err1 and err2 so I can build the code.

I have been over the docs but there is a lot to take in and must have missed how the err variable is being able to be re-used, or have I completely misunderstood something?

Thanks,

You redeclared the variable err. What you often see is the shorter error handling syntax:

if err := DoSomething(); err != nil {
    // handle
}

Variables declared in control structures and for loops are only visible to that block. So the err declared above can only be seen within the if block.

You can treat your error has like this.

if err := r.ParseForm(); err != nil {
    log.Panic(err)
}

var user User
if err := decoder.Decode(&user, r.PostForm); err != nil {
    log.Panic(err)
}

Or define your error globally.

var err error
err = r.ParseForm()