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

builtin: append replaces values #53795

Closed
Vector-Hector opened this issue Jul 11, 2022 · 5 comments
Closed

builtin: append replaces values #53795

Vector-Hector opened this issue Jul 11, 2022 · 5 comments

Comments

@Vector-Hector
Copy link

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

$ go version
go version go1.18.3 windows/amd64

What did you do?

Play

arr := []string{"a", "b", "c"}
_ = append(arr[:2], "e")
	
fmt.Println(arr)

Result:
["a", "b", "e"]

What did you expect to see?

I expected append to create a new slice, that is ["a", "b", "e"]. I did not expect append to change the original slice arr as it does not target that slice. If I instead use append(arr[:2], "e", "f"), it does not change arr (as expected).

What did you see instead?

The slice arr changed its third value from "c" to "e".

@mdlayher
Copy link
Member

Working as intended, you need to use the result of append as it may reallocate the underlying array if there is insufficient space for new elements.

@mdlayher
Copy link
Member

@Vector-Hector
Copy link
Author

I disagree. arr[:2] does not have the capacity to store a new element. So by the documentation, it should allocate a new array and not change arr for some reason. However, if it is intended, I'll just keep in mind, that append may change other slices too.

@seankhliao
Copy link
Member

Unlike many projects, the Go project does not use GitHub Issues for general discussion or asking questions. GitHub Issues are used for tracking bugs and proposals only.

For questions please refer to https://github.com/golang/go/wiki/Questions

@timothy-king
Copy link
Contributor

@Vector-Hector arr[:2] does have the capacity to store "e". Use the 3 argument form of a slice expression, a[low : high : max], if you intend on controlling capacity: https://go.dev/ref/spec#Slice_expressions.

https://play.golang.com/p/UNFoS592mq5 prints "3 vs 2":

func main() {
	c := []string{"a", "b", "c"}
	fmt.Println(cap(c[:2]), " vs ", cap(c[:2:2]))
}

@golang golang locked and limited conversation to collaborators Jul 11, 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

5 participants