Golang变量分配

Is there a way in go to assign two variables to a function that returns two values when you have one variable declared and the other not.

For example:

var host string
if host, err := func(); err != nil {}

In the above code, host is declared but err isn't. I want a clean way to do this other than declaring err

In your example you simply shouldn't be declaring host. There is no way to do partial assignment like that... Either your using := which is short hand for declaration and assignment or you using = and you're doing assignment only. I personally very rarely write the word var in Go.

To be clear, if you have one variable that has already been declared with one or more that have not, you're allowed to use := to assign to it, but the inverse is not true. Meaning you cannot use = if one or more of the left hand side values haven't been declared already.

When you use := in an if like that, you will always get new variables declared in the scope of the if. Following the if, the value of host will be the same as it was before. If you want to do this, you need to declare both host and err before the if (and don't use := in the if).