The difference between range operation array and slice

1. First, you need to understand deep and shallow copy: https://www.jianshu.com/p/372218aff8ef
2. When using range, you can't always grasp the value of value. Use an example to understand the operation reference type and value type Have a difference. (The same code only differs from array and slice)
Example 1:

func main() {
    
    
	a := []int{
    
    1, 2, 3}
	for i, v := range a {
    
    
		fmt.Println("&v", &v)
		if i == 0 {
    
    
			a[1], a[2] = 200, 300
			fmt.Println("&a", &a[1])
		}
		fmt.Println("v", v)
	}
	fmt.Println("a", a)
}

Example one result:

&v 0xc0000a0068
&a 0xc00009e128
v 1
&v 0xc0000a0068
v 200
&v 0xc0000a0068
v 300
a [1 200 300]

Example 2: (just modified the type of a)

func main() {
    
    
	a := [3]int{
    
    1, 2, 3}
	for i, v := range a {
    
    
		fmt.Println("&v", &v)
		if i == 0 {
    
    
			a[1], a[2] = 200, 300
			fmt.Println("&a", &a[1])
		}
		fmt.Println("v", v)
	}
	fmt.Println("a", a)
}

Example two result:

&v 0xc0000120a0
&a 0xc00000a408
v 1
&v 0xc0000120a0
v 2
&v 0xc0000120a0
v 3
a [1 200 300]

You can draw a conclusion by carefully comparing the two print results.

Conclusion: When using range to manipulate reference types (slice, map), changes in the traversal object (a in the example) will affect the value of value (v in the example). (Shallow copy)
Conversely, when using the range operation value type (array, int, string, struct, float, bool), the change of the traversal object (a in the example) will not affect the value (v in the example) Value. (Deep copy)

Guess you like

Origin blog.csdn.net/qq_43234632/article/details/105891942