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

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

问题描述

为什么会发生以下行为:

$ p $ a:= [] int {1,2,3} $ b $ (a [2:])
fmt.Println(a [3:0])
fmt.Println(a [1:])
fmt.Println :])//不会恐慌 - 为什么?
fmt.Println(a [4:])//如预期的那样恐慌

可执行示例

解决方案

a [3:] 构建一个空片段,就像空数组一样,它是一个有效且有用的对象(在所有语言中,不仅限于Go) 。

一个空片还指向一个底层数组,一个位置和一个容量,有时可以扩展:

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

另一方面,长度为负的片段不一致。这意味着什么,因此被禁止。


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

Executable example

解决方案

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天全站免登陆