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

Using slice doesn't work properly #52152

Closed
acumino opened this issue Apr 5, 2022 · 1 comment
Closed

Using slice doesn't work properly #52152

acumino opened this issue Apr 5, 2022 · 1 comment

Comments

@acumino
Copy link

acumino commented Apr 5, 2022

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

Both 1.17 and 1.18

Does this issue reproduce with the latest release?

Yes

What did you do?

Using slices in recursion and assigning its values to some value in any struct.

See here: https://go.dev/play/p/iUZ5tF5AUJP

The correct printed value should be

[{[value1 value1 value1 value1 value1 value2 value3]}]

But it is printing

[{[value1 value1 value1 value1 value1 value3 value3]}]

The same thing works fine if we don't use any struct.

See here: https://go.dev/play/p/d3ZLQTDPeoy

In this case the printed value is

[value1 value1 value1 value1 value1 value2 value3]
@randall77
Copy link
Contributor

This is how slices work. Append does not always make a copy, but often appends in place.
See https://go.dev/blog/slices-intro for more background.

This patch fixes your code:

	if len(a) == 7 {
		a2 := make([]string, len(a))
		copy(a2, a)
		res := test{l: a2}

@golang golang locked and limited conversation to collaborators Apr 5, 2023
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

3 participants