Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
ionnss opened this issue Oct 7, 2024 · 0 comments
Open

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

ionnss opened this issue Oct 7, 2024 · 0 comments

Comments

@ionnss
Copy link

ionnss commented Oct 7, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant