언어/Golang

Slice length and capacity (슬라이스의 길이와 용량)

SYeonni 2022. 8. 3. 11:53
package main

import "fmt"

func main() {
   s := []int{2, 3, 5, 7, 11, 13}
   printSlice(s)

   // Slice the slice to give it zero length.
   s = s[:0]
   printSlice(s)

   // Extend its length.
   s = s[:4]
   printSlice(s)

   // Drop its first two values.
   s = s[2:]
   printSlice(s)
}

func printSlice(s []int) {
   fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

 

 

마지막 cap이 4가 나와 헷갈렸음..

나뿐만 아니라 다른사람도 헷갈렸음 ㅠㅠ

친절한 답변으로 이해함!

https://stackoverflow.com/questions/36683911/go-slices-capacity-length

 

Go slices - capacity/length?

Trying to learn Go from the tutorial right now, and have a pretty basic question: func main() { a := make([]int, 5) // [0,0,0,0,0] len=5 cap=5 b := make([]int, 0, 5) // [] len=0 cap=5 ...

stackoverflow.com

 

728x90