goLang slice에서 cap의 개념을 발견하다.
goLang Tour의 slice를 해보고 있었다.
slice라는 것은 python에서도 자연스러운 것이었으나, goLang에서 가장 크게 혼동되는 것은 cap이라는 개념이 있는 것 + 기존 slice에 append하는 경우에, cap이 모자라면 +1이 아니라 +2 해서 생성이 되는 것을 발견한다.
이거 생각 잘 하고. 그 특성을 이해 하고 써야겠는걸?
package main
import "fmt"
func main() {
var s []int
printSlice(s)
// append wprks on nil slices
s = append(s, 0)
printSlice(s)
// append를 하면 len==1이 되는 것은 당연해 보이는데, cap==2가 되는 이유는 무엇일까?
// len을 강제로 2로 변경 해 보면 늘어나는 것을 볼 수 있다.
// s = s[:2]
// printSlice(s)
// The slice grows as needed
// 위에서는 nil에서 append하면 cap==2가 되었는데. cap==2인 상태에서 append하면 여전히 2이다.
// 뭔가 규칙이 있나?
s = append(s, 1)
printSlice(s)
// We can add more than one element at a time
// cap이 apped결과보다 작을 경우에, cap+1이 되어 생성되는 것으로 보인다.
s = append(s, 2, 3, 4)
printSlice(s)
// 강제로 len을 설정하면. 마지막은 0으로 되어 있는 것을 볼 수 있다. nil이 아니다.
s = s[:cap(s)]
printSlice(s)
}
func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
Enjoy Reading This Article?
Here are some more articles you might like to read next: