Closed wangfengfly closed 2 years ago
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
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
I encountered a bug, when appending an item to a 2d slice, this is not a question, but a possible bug, please help and have a look at the issue? thank you
@wangfengfly sorry, this is a bug in your code, caused by an erroneous understanding of what slices are. Slices are just views over a backing array. When you append to a slice, the backing array changes. Your program has multiple slices sharing the same backing array. Consider:
func main() {
arr := []int{1, 2, 3, 4, 5}
slice := arr[0:3]
fmt.Println(arr) // prints [1 2 3 4 5]
slice = append(slice, 5)
fmt.Println(arr) // prints [1 2 3 5 5]
}
This is roughly what's happening in your code. Please see the link above if you have further questions.
@wangfengfly sorry, this is a bug in your code, caused by an erroneous understanding of what slices are. Slices are just views over a backing array. When you append to a slice, the backing array changes. Your program has multiple slices sharing the same backing array. Consider:
func main() { arr := []int{1, 2, 3, 4, 5} slice := arr[0:3] fmt.Println(arr) // prints [1 2 3 4 5] slice = append(slice, 5) fmt.Println(arr) // prints [1 2 3 5 5] }
This is roughly what's happening in your code. Please see the link above if you have further questions.
Oh, sorry, it is indeed my code fault, thank you very much.
ok, thank you very much.
What version of Go are you using (
go version
)?Does this issue reproduce with the latest release?
Not sure
What operating system and processor architecture are you using (
go env
)?go env
OutputWhat did you do?
Given an integer array nums of unique elements, return all possible subsets (the power set). The leetcode problem link: https://leetcode.com/problems/subsets/
What did you expect to see?
[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3],[4],[1,4],[2,4],[1,2,4],[3,4],[1,3,4],[2,3,4],[1,2,3,4],[5],[1,5],[2,5],[1,2,5],[3,5],[1,3,5],[2,3,5],[1,2,3,5],[4,5],[1,4,5],[2,4,5],[1,2,4,5],[3,4,5],[1,3,4,5],[2,3,4,5],[1,2,3,4,5]]
What did you see instead?
[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3],[4],[1,4],[2,4],[1,2,4],[3,4],[1,3,4],[2,3,4],[1,2,3,5],[5],[1,5],[2,5],[1,2,5],[3,5],[1,3,5],[2,3,5],[1,2,3,5],[4,5],[1,4,5],[2,4,5],[1,2,4,5],[3,4,5],[1,3,4,5],[2,3,4,5],[1,2,3,5,5]]
When appending the last item of the array to the subsets[7], in this case whose value is 5, the subsets[15] is also updated!
For debugging purpose, i write the debug code which is commented out above to reproduce this bug. Please , Thank you very much.