1. The same root copy
func main() { nums := [3]int{} nums[0] = 1 ("nums: %v , len: %d, cap: %d\n", nums, len(nums), cap(nums)) dnums := nums[0:2] dnums[0] = 5 ("nums: %v ,len: %d, cap: %d\n", nums, len(nums), cap(nums)) ("dnums: %v, len: %d, cap: %d\n", dnums, len(dnums), cap(dnums)) }
Output:
nums: [1 0 0] , len: 3, cap: 3
nums: [5 0 0] ,len: 3, cap: 3
dnums: [5 0], len: 2, cap: 3
If the slice is not a deep copy or a new space is regenerated, it has the same root nature whether it is passed through parameters or used := or [:] assignment.
2. Expand capacity and get rid of the same roots
The biggest difference between Slice and Array is that Slice does not need to specify a size and automatically expands its capacity. After we accept and get used to the same nature, we have to do so. When Slice appends elements multiple times, if the expansion strategy is met, it will reapply a piece of memory space internally and copy the original element to the new memory space. At this time, it has no relationship with the original array, and the value will not change to the original array after modification.
func main() { nums := [3]int{} nums[0] = 1 ("nums: %v , len: %d, cap: %d\n", nums, len(nums), cap(nums)) dnums := nums[0:2] dnums = append(dnums, []int{2, 3}...) dnums[1] = 1 ("nums: %v ,len: %d, cap: %d\n", nums, len(nums), cap(nums)) ("dnums: %v, len: %d, cap: %d\n", dnums, len(dnums), cap(dnums)) }
Output:
nums: [1 0 0] , len: 3, cap: 3
nums: [1 0 0] ,len: 3, cap: 3
dnums: [1 1 2 3], len: 4, cap: 6
3. Empty and nil
Empty
func main() { nums := []int{} renums := make([]int, 0) ("nums: %v, len: %d, cap: %d\n", nums, len(nums), cap(nums)) ("renums: %v, len: %d, cap: %d\n", renums, len(renums), cap(renums)) }
Output:
nums: [], len: 0, cap: 0
renums: [], len: 0, cap: 0
nil
func main() { var nums []int (nums,len(nums),cap(nums)) }
Output
[] 0 0
From the output we will find that both data, len and cap are the same output content.
Then let's use code to prove whether they are really consistent.
func main() { var nums []int renums := make([]int, 0) if nums == nil { ("nums is nil.") } if renums == nil { ("renums is nil.") } }
Output:
nums is nil.
Is the output unexpected? But smart, you must have thought of the answer through your own experience.
One has allocated space (Empty) and the other has no allocated space (nil)
The above is the pitfall I encountered when using slice, and I will no longer do special analysis for maps here.
This is the end of this article about the pitfalls of Golang Slice and map. For more information about Golang Slice and map, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!