简体   繁体   English

如何检查数组索引是否存在于go中

[英]How to check if array index exists in go

I am coming from javascript and know how to check if a variable exists.我来自 javascript 并且知道如何检查变量是否存在。 We can use !!var我们可以使用!!var

I have come across an array in Go where I want to know if an index exists:我在 Go 中遇到了一个数组,我想知道索引是否存在:

myArr := []int{1, 2, 3}

if myArr[3] {
  fmt.Println("YES")
}

When I run this it gives me an error: Index Out Of Range: 3当我运行它时,它给了我一个错误: Index Out Of Range: 3

Since Go is a compiled language the concept of a variable not existing does not make sense.由于 Go 是一种编译语言,因此不存在变量的概念没有意义。 The closest thing is that some types can take a nil value.最接近的是某些类型可以采用 nil 值。

As far as arrays go they just have a length (without gaps).就数组而言,它们只有一个长度(没有间隙)。 So if the length is N then only indices 0 to N-1 are valid.因此,如果长度为 N,则只有索引 0 到 N-1 有效。 The built-in len() function works with any array or slice.内置的 len() 函数适用于任何数组或切片。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM