切片的零值不是零

编程入门 行业动态 更新时间:2024-10-25 20:25:16
本文介绍了切片的零值不是零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我按照以下示例 tour.golang/moretypes/10 我修改了希望得到相同结果的代码。我没有。这是一个错误还是文档错误?旅游状态

I was following the example tour.golang/moretypes/10 I modified the code expecting to get the same result. I did not. Is this a bug, or a documentation error? The tour states

一个零切片的长度和容量为0

A nil slice has a length and capacity of 0.

我的y变量的长度和容量都是0.

My y variable has a length and capacity of 0.

package main import "fmt" func myPrint(z []int) { fmt.Println(z, len(z), cap(z)) if z == nil { fmt.Println("nil!") } } func main() { var z []int y := []int {} myPrint(z) myPrint(y) }

这是我的输出。

[] 0 0 nil! [] 0 0

我期待第二个零〜为什么没有我得到了它?

I was expecting a second "nil"~ Why didn't I get it?

推荐答案

您引用的doc指出 nil slice的长度和容量均为0 ,但不是每个长度和零容量片都是零片。

The doc you referenced to states that A nil slice has a length and capacity of 0 but not that every slice of length and capacity of zero is a nil slice.

这支持 len 和 cap 指向未指定(nil)的指针(片)。否则,我们需要首先检查非零。

This is a convenience to support len and cap on pointers (of slices) which are unassigned (nil). Otherwise we would need to check for non-nil first.

指针是理解我认为的问题的关键词。在第一种情况下,你有一个零指针,在第二种情况下你已经分配了slice,但它是空的。这可以适用于任何结构:

Pointer is key word here to understand the problem I think. In the first case you have a nil pointer, in the second case you have allocated slice, but it's empty. This would hold for any structure:

package main import "fmt" func main() { var s *struct{} fmt.Println(s) // <nil> s = &struct{}{} fmt.Println(s) // &{} }

更多推荐

切片的零值不是零

本文发布于:2023-11-02 08:05:06,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:切片

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!