Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
947 views
in Technique[技术] by (71.8m points)

arrays - 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

  c := b[:2]
  // [0,0] len=2 cap=5

  d := c[2:5]
  // [0,0,0] len=3 cap=3
}

Why does c look like [0,0] and have length 2? b was not originally zero'ed hence it being []. So does setting c to b[:2] zero out the first two elements?

Also, why is the capacity of d 3? Very confused.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...