Posts Golang Slice
Post
Cancel

Golang Slice

Slice


๐Ÿ’ฟ Array

An array type definition specifies a length and an element type.

image

  • 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)์„ ๊ฐ€์ง€๋Š” ๊ฐ’ํƒ€์ž… ๋ณ€์ˆ˜

image

  • ์ด๊ฒƒ๋„ ํฌ์ธํ„ฐ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์„ ๋ฟ์ด์ง€ ๊ฐ’ํƒ€์ž… ๋ณ€์ˆ˜์ด๋‹ค.(์ฐธ์กฐํ˜• ๋ณ€์ˆ˜ ์•„๋‹˜)
  • 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์„ ๋„˜์ง€ ์•Š์œผ๋ฉด ์ƒˆ๋กœ์šด ๋ฐฐ์—ด์ด ์ƒ์„ฑ๋˜์ง€๋Š” ์•Š์Œ
This post is licensed under CC BY 4.0 by the author.

Prometheus 1

Golang Slice