Go 只有值传递

Slice底层数据结构

1
2
3
4
5
type slice struct {
array unsafe.Pointer
len int
cap int
}

Slice图解

Untitled

Slice扩容原理

  • cap < 1024时每次扩容一倍
  • cap ≥ 1024是每次扩容1.25倍
1
2
3
4
5
6
7
8
9
var s []int // len: 0 cap: 0
s = append(s, 0) // len: 1 cap: 1

s = append(s, 1) // len: 2 cap: 2
s = append(s, 2) // len: 3 cap: 4

for i := 3; i < 1025; i++ { // len: 1025 cap: 1280
s = append(s, i)
}

值传递演示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package main

import "fmt"

func main() {
Case1()
Case2()
Case3()
}

func Case1() {
var s []int
for i := 0; i < 3; i++ {
s = append(s, i)
}
modifySlice1(s)
fmt.Printf("case1: %v\n", s)
}

func Case2() {
var s []int
for i := 0; i < 3; i++ {
s = append(s, i)
}
modifySlice2(s)
fmt.Printf("case2: %v\n", s)
}

func Case3() {
var s []int
for i := 0; i < 3; i++ {
s = append(s, i)
}
modifySlice3(s)
fmt.Printf("case3: %v\n", s)
}

func modifySlice3(s []int) {
s = append(s, 2048)
s = append(s, 4096)
fmt.Printf("modifySlice3 len: %v, cap: %v\n", len(s), cap(s))
s[0] = 1024
}

func modifySlice2(s []int) {
s = append(s, 2048)
fmt.Printf("modifySlice2 len: %v, cap: %v\n", len(s), cap(s))
s[0] = 1024
}

func modifySlice1(s []int) {
s[0] = 1024
}
1
2
3
4
5
case1: [1024 1 2]
modifySlice2 len: 4, cap: 4
case2: [1024 1 2]
modifySlice3 len: 5, cap: 8
case3: [0 1 2]
  • 如果没有发生扩容修改在原来的内存当中
  • 如果发生了扩容修改在新的内存当中