为什么 go 允许从 len(slice) 切片? [英] Why does go allow slicing from len(slice)?

查看:46
本文介绍了为什么 go 允许从 len(slice) 切片?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么会出现以下行为:

Why does the following behavior occur:

a := []int{1, 2, 3}
fmt.Println(a[0:])
fmt.Println(a[1:])
fmt.Println(a[2:])
fmt.Println(a[3:])// doesn't panic - why??
fmt.Println(a[4:])// panics as expected

可执行示例

推荐答案

a[3:] 构建一个空切片,它就像一个空数组,是一个有效且有用的对象(在所有语言,而不仅仅是 Go).

a[3:] builds an empty slice which, just like an empty array, is a valid and useful object (in all languages, not just in Go).

空切片也仍然指向底层数组、位置和容量,有时可以扩展:

An empty slice also still points to an underlying array, a position and a capacity and can sometimes be extended:

a := []int{1, 2, 3}
emptySlice := a[1:1]
fmt.Println(emptySlice) // []
notEmpty := emptySlice[0:2]
fmt.Println(notEmpty)   // [2 3]

另一方面,长度为负的切片不一致.它没有任何意义,因此被禁止.

On the other end, a slice with a negative length is inconsistent. It means nothing and thus is forbidden.

这篇关于为什么 go 允许从 len(slice) 切片?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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