去切片 - 容量/长度? [英] Go slices - capacity/length?

查看:42
本文介绍了去切片 - 容量/长度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在正在尝试从教程中学习 Go,并有一个非常基本的问题:

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
}

为什么 c 看起来像 [0,0] 并且长度为 2?b 最初没有归零,因此它是 [].那么将 c 设置为 b[:2] 是否会将前两个元素归零?

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?

另外,为什么d的容量是3?很迷茫.

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

提前致谢.

推荐答案

你所有的变量都有一个 切片类型.切片有一个支持 array.在 Go 中,您无法访问未初始化的变量.如果您在创建新变量时没有明确提供值,它们将被初始化为 零值 变量的类型.

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.

这意味着当您使用 make([]int, 0, 5) 创建切片时,它也会创建一个支持数组,支持数组将以其零值初始化,并将其归零数组将被切片.数组类型的零值是一个数组,它的每个元素都具有元素类型的零值.

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.

因此,即使您没有明确地将支持数组的每个元素设置为 0,它们也会自动归零.所以当你做 c := b[:2] 时,它会对 b 切片进行切片,并且 c 的长度为 2,这两个元素将是 0.

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.

当你执行 d := c[2:5]c 切片进行切片时,它的长度将为 5-2 = 3code>,它的容量也将是 5-2 = 3 因为切片将导致一个新的切片 共享相同的后备数组,并且容量将为第一个元素直到支持数组的最后一个元素(除非您使用完整切片表达式,它也控制生成的切片的容量).

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:

Go 博客:Go Slices:用法和内部结构

Go 博客:数组、切片(和字符串):追加"的机制

这篇关于去切片 - 容量/长度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆