if statement

suggest change

A simple if statement:

func returnValues(ok bool) (int, bool) {
	return 5, ok
}

func main() {
	a := 5
	b := 5
	if a == b {
		fmt.Print("a is equal to b\n")
	} else {
		fmt.Print("a is not equal to b\n")
	}

	if n, ok := returnValues(true); ok {
		fmt.Printf("ok is true, n: %d\n", n)
	} else {
		fmt.Printf("ok is false, n: %d\n", n)
	}
}
a is equal to b
ok is true, n: 5

A variable declared in if statement is scoped to that statement. This example fails to compile because of that:

func returnValues(ok bool) (int, bool) {
	return 5, ok
}

func main() {
	if n, ok := returnValues(true); ok {
		fmt.Print("ok is true, n: %d\n", n)
	} else {
		fmt.Print("ok is false, n: %d\n", n)
	}

	// n is only visible within if statement, so this fails compilation
	fmt.Printf("n: %d\n", n)
}
# test
./main.go:19:24: undefined: n
exit status 2

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents