Why is this a valid program?
package main
import "fmt"
func giveMeError(limit int) ([]string, error) {
return nil, fmt.Errorf("MY ERROR %d", limit)
}
func main() {
res1, err := giveMeError(1)
if err == nil {
fmt.Println("res", res1)
} else {
fmt.Println("err", err)
}
res2, err := giveMeError(5)
if err == nil {
fmt.Println("res", res2)
} else {
fmt.Println("err", err)
}
}
And this isn't?
package main
import "fmt"
func giveMeError(limit int) ([]string, error) {
return nil, fmt.Errorf("MY ERROR %d", limit)
}
func main() {
res, err := giveMeError(1)
if err == nil {
fmt.Println("res", res)
} else {
fmt.Println("err", err)
}
res, err := giveMeError(5)
if err == nil {
fmt.Println("res", res)
} else {
fmt.Println("err", err)
}
}
Complains that ./main.go:18: no new variables on left side of :=
I thought :=
cannot be used to change value to existing variables?
In Go language, you are allowed to return multiple values from a function, using the return statement. Or in other words, in function, a single return statement can return multiple values. The type of the return values is similar to the type of the parameter defined in the parameter list.
Functions in Golang can return multiple values, which is a helpful feature in many practical scenarios. This example declares a function with two return values and calls it from a main function.
Below are the methods to return multiple values from a function in C: By using pointers. By using structures. By using Arrays.
A function can have more than one return statement, but only ever run one based on a condition.
The documentation is clear at this point:
In a := declaration a variable v may appear even if it has already been declared, provided:
this declaration is in the same scope as the existing declaration of v (if v is already declared in an outer scope, the declaration will create a new variable §), the corresponding value in the initialization is assignable to v, and there is at least one other variable in the declaration that is being declared anew.
klashxx already answer the question.
There may be something confusing here.
package main
import "fmt"
func main(){
a, b := 1, 2
fmt.Println(a, b)
{
b, c := 100, 200 //NOTE: b here is a new variable
fmt.Println(a, b, c)
}
fmt.Println(a, b)
b, c := 1000, 2000
fmt.Println(a, b, c)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With