Slice
๐ฟ Array
An array type definition specifies a length and an element type.
- Goโs arrays are values.
- it is not a pointer to the first array element (as would be the case in C).
- This means that when you assign or pass around an array value you will make a copy of its contents.
- To avoid the copy you could pass a pointer to the array, but then thatโs a pointer to an array, not an array.
1
2
3
4
5
func main() {
arr := [...]int{1,2,3,4,5}
fmt.Printf("%v, %p\n", arr, &arr)
}
// result: [1 2 3 4 5], 0xc000122030
์ฆ Array์ ํฌ์ธํฐ๋ฅผ ์ฌ์์ฉ ์ ์์ง๋ง C ์ฒ๋ผ Array ํ์ ์ ์ฃผ์๊ฐ์ ๊ฐ์ง์ง ์๊ณ , ๊ฐ์ ๊ทธ๋๋ก ๊ฐ์ง๋ค.
๐ฟ Slice
์ฐ์์ ๋ฐ์ดํฐ์ ๋ฉํ๋ฐ์ดํฐ(์ฃผ์, len, cap)์ ๊ฐ์ง๋ ๊ฐํ์ ๋ณ์
- ์ด๊ฒ๋ ํฌ์ธํฐ๋ฅผ ๊ฐ์ง๊ณ ์์ ๋ฟ์ด์ง ๊ฐํ์ ๋ณ์์ด๋ค.(์ฐธ์กฐํ ๋ณ์ ์๋)
- Array๋ฅผ ์๋ผ์ Slice๊ฐ ๋๋ ๊ฐ๋
์ด ์๋ Array์ ๋ฉํ๋ฐ์ดํ๋ฅผ ๋ฝ์์ Sliceํ์
์ผ๋ก ๋ณํํ๋ ๊ฐ๋
- ๋ฏธ๋ฌํ์ง๋ง ์ด๊ฐ ์ฐจ์ด์ธ๊ฒ ๊ฐ์โฆ
- ์์ฑ ํจ์: func make([]T, len, cap) []T
์ฆ๋ช
1
2
3
4
5
6
7
8
9
10
func main() {
arr := [...]int{1,2,3,4,5}
slice1 := arr[:]
slice2 := arr[:]
fmt.Printf("%p %p \n", &slice1, &slice2)
fmt.Printf("%p %p \n", slice1, slice2)
}
// 0xc0000ac018 0xc0000ac030 (slice1,2์ ์ฃผ์)
// 0xc0000b0030 0xc0000b0030 (slice1,2๊ฐ ๊ฐ์ง ๋ฐฐ์ด ์ฃผ์)
- ์ฆ ๋ฉํ๋ฐ์ดํฐ๋ฅผ ๋ฝ์์ Slice๋ฅผ ์์ฑํ๋ฉด ๋งค๋ฒ ์๋ก์ด Slice(๋ค๋ฅธ ์ฃผ์)๊ฐ ์์ฑ
- ํ์ง๋ง ์์ฑ๋ Slice๊ฐ ๊ฐ์ง๋ ๋ฐฐ์ด์ ๋ชจ๋ ๊ฐ์ ๋์
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
func main() {
arr := [...]int{1,2,3,4,5}
slice1 := arr[:]
fmt.Printf("%p %p %d %d \n", &slice1, slice1, len(slice1), cap(slice1))
slice2 := append(slice1, 6)
fmt.Printf("%p %p %d %d \n", &slice2, slice2, len(slice2), cap(slice2))
slice21 := append(slice2, 7)
fmt.Printf("%p %p %d %d \n", &slice21, slice21, len(slice21), cap(slice21))
slice3 := append(slice2, 8,9,10,11)
fmt.Printf("%p %p %d %d \n", &slice3, slice3, len(slice3), cap(slice3))
slice4 := append(slice3, 12,13,14,15,16,17,18,19,20,21)
fmt.Printf("%p %p %d %d \n", &slice4, slice4, len(slice4), cap(slice4))
}
/*
result:
0xc000126018 0xc00012a030 5 5
0xc000126048 0xc000138000 6 10
0xc000126078 0xc000138000 7 10
0xc0001260a8 0xc000138000 10 10
0xc0001260d8 0xc00013c000 20 20
*/
- cap๋ฅผ ๋์ ๋ ๋ง๋ค ์๋ก์ด ์ฃผ์๋ฅผ ๊ฐ์ง ๋ฐฐ์ด์ด ํ ๋น๋จ
- appendํ ๋๋ง๋ค ์๋ก์ด slice๊ฐ ์์ฑ๋์ง๋ง cap์ ๋์ง ์์ผ๋ฉด ์๋ก์ด ๋ฐฐ์ด์ด ์์ฑ๋์ง๋ ์์