golang/tour

tour: [Error when running example code in NAMED RETURN VALUES]

Opened this issue · 0 comments

Context: https://go.dev/tour/basics/7

In the Named return values section (7/17) of the Go Tour, the following function is provided:

func split(sum int) (x, y int) {
	x = sum * 4 / 9
	y = sum - x
	return
}

And the main function that splits 17 is shown as:

func main() {
	fmt.Println(split(17))
}

However, when you run this code in a local Go environment (e.g., in your own file and terminal), the following error appears:

~% go run hello.go
# command-line-arguments
./hello.go:39:46: multiple-value split(17) (value of type (x int, y int)) in single-value context

Cause of the Issue:
The issue arises because fmt.Println(split(17)) attempts to use the result of split in a single-value context, but split returns two values (x and y).

Proposed Fix:
To resolve this, the values returned by split should be captured in separate variables:

func main() {
	x, y := split(17)
	fmt.Println("Split 17:", x, y)
}

This code correctly handles the multiple return values and prints the expected output.