dongsui5464 2016-04-18 00:56
浏览 24

去切片-容量/长度?

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.

  • 写回答

1条回答 默认 最新

  • 普通网友 2016-04-18 09:15
    关注

    All your variables have a slice type. Slices have a backing array. In Go you can't access uninitialized variables. If you don't explicitly provide a value when you create a new variable, they will be initialized with the zero value of the variable's type.

    This means when you create a slice with make([]int, 0, 5), it also creates a backing array, the backing array will be initialized with its zero value, and this zeroed array will be sliced. The zero value of an array type is an array having the zero value of element type for each of its elements.

    So even though you didn't explicitly set every elements of the backing array to 0, they will be zeroed automatically. So when you do c := b[:2], it will slice the b slice, and c will have a length of 2, and those 2 elements will be 0.

    And when you do d := c[2:5] that slices the c slice, its length will be 5-2 = 3, and its capacity will also be 5-2 = 3 because slicing a slice will result in a new slice which shares the same backing array, and the capacity will be the first element till the last of the backing array (unless you use a full slice expression which also controls the resulting slice's capacity).

    Must-read blog posts for newcomers who want to understand slices and arrays:

    The Go Blog: Go Slices: usage and internals

    The Go Blog: Arrays, slices (and strings): The mechanics of 'append'

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度