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

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

问题描述

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

  func main(){
a:= make([] int,5)
// [0,0,0,0,0] len = 5 cap = 5
$ bb:= 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
}

$ b为什么 c < 并且长度为2? b 最初不是零,因此它是 [] 。因此,设置 c b [:2] 是否将前两个元素设为零?



另外,为什么 d 3的容量?非常困惑。



预先感谢您。

切片类型。切片有数组的支持。在Go中,您无法访问未初始化的变量。如果您在创建新变量时未明确提供值,则会使用零值
$ b 这意味着当你使用 make([] int,0,5)创建一个片段时,它也创建一个后备数组,后备数组将被初始化为零值,并且这个归零数组将会是
切片。数组类型的零值是一个数组,其每个元素的元素类型都为零。



因此,即使您没有明确设置每个元素支持数组< 0 ,它们将自动归零。因此,当您执行 c:= b [:2] 时,它将切分 b 切片, c 的长度为2,这两个元素的长度为 0



当您执行切分 c 切片的 d:= c [2:5] 时,其切片长度将为 5-2 = 3 ,其容量也将 5-2 = 3 ,因为切片将会产生一个新的片段,它共享相同的后备数组,并且容量将是直到最后一个后备数组的第一个元素(除非使用完整的片段表达式 这也控制了结果切片的容量)。



需要了解切片和数组的新手必读博客文章:

Go博客:Go Slices:使用和内部消息 strong>



Go博客:阵列,s lices(和字符串):'append'的机制


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.

解决方案

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'

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

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