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

Cannot redefine existing variables inside an if statement when ":=" is required #58147

Closed
MarkGaskinRR opened this issue Jan 30, 2023 · 5 comments

Comments

@MarkGaskinRR
Copy link

What version of Go are you using (go version)?

Reproducible in go.dev/play with Go 1.19

$ go version
1.19

Does this issue reproduce with the latest release?

Yes

What operating system and processor architecture are you using (go env)?

Just using go.dev/play here

What did you do?

https://go.dev/play/p/VF4NlYvP7ce

func generateNumberAndError() (int, error) {
	return 1, errors.New("Test")
}

func main() {
	var err error
	if true {
		i, err := generateNumberAndError()
		fmt.Println(i)
		fmt.Println(err)
	}

	fmt.Println(err) // Expecting "Test", but receiving nil
}

What did you expect to see?

"Test"

What did you see instead?

nil

Workarounds

func generateNumberAndError() (int, error) {
	return 1, errors.New("Test")
}

func main() {
	var err error
	var i int
	if true {
		i, err = generateNumberAndError()
		fmt.Println(i)
		fmt.Println(err)
	}

	fmt.Println(err) // Works
}

But this is not feasible for situations where multiple return values are needed. It would unnecessarily bloat the code.

@seankhliao
Copy link
Member

Working as intended for the spec.

@seankhliao seankhliao closed this as not planned Won't fix, can't repro, duplicate, stale Jan 30, 2023
@MarkGaskinRR
Copy link
Author

MarkGaskinRR commented Jan 30, 2023

Can you link where in the spec I would find this @seankhliao ?

@randall77
Copy link
Contributor

@MarkGaskinRR
Copy link
Author

Thanks @randall77 and @seankhliao.

I'll just note for me, this is unintuitive behaviour worth reconsidering.

@ianlancetaylor
Copy link
Member

@MarkGaskinRR Lots of discussion in #377.

It's unlikely that we can change any of this behavior now.

@golang golang locked and limited conversation to collaborators Jan 30, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants