英文:
Test Index out of range golang
问题
抱歉,这是一个初学者问题,但我不确定如何测试我正在访问的元素是否对数组有效。请考虑以下虚构的代码:
func main() {
strings := []string{"abc", "def", "ghi", "jkl"}
for i := 0; i<5; i++ {
if strings[i] {
fmt.Println(strings[i])
}
}
}
我显然超出了边界,但我不确定如何测试以防止错误。我习惯于使用PHP,我会使用isset
或!empty
测试,Go语言有类似的功能吗?
我浏览了其他问题并看到了使用len
函数,但似乎不起作用。
英文:
Sorry for this noob question, but I'm not sure how I test to see if an element I'm accessing is valid for an array, consider the following contrived code:
func main() {
strings := []string{"abc", "def", "ghi", "jkl"}
for i := 0; i<5; i++ {
if strings[i] {
fmt.Println(strings[i])
}
}
}
https://play.golang.org/p/8QjGadu6Fu
I'm obviously going outside of the bounds, but I'm not sure how I test to prevent the error. I'm used to PHP where I would use an isset
or !empty
test, does go have such a thing?
I've browsed other questions and seen the len
function used, but that doesn't appear to work.
答案1
得分: 43
在Go语言中,这并不像在PHP中那么容易 - 但请记住,在PHP中之所以容易,是因为“索引”数组实际上是关联数组。否则,您将无法通过取消设置单个元素来“打洞”到数组中。
对于Go的数组/切片,您必须实际检查数组的长度,就像您写的那样:
if i>=0 && i<len(strings) {...}
就个人而言,我还没有遇到过需要这样做的真实情况 - 在您的示例中,您可以使用range(strings)
,不再担心索引。
对于映射,它们是Go中与PHP数组等效的数据结构,您可以通过编写以下代码来进行“isset”操作:
value, isset := map[index]
如果index
存在于映射中,value
将被适当设置,并且isset
将为true;如果不存在,则value
将被设置为映射类型的零值,并且isset
将为false。
英文:
In Go, this is not quite as easy as in PHP - but keep in mind that in PHP it's only easy because "indexed" arrays are actually associative arrays under the hood. Otherwise you wouldn't be able to "punch holes" into arrays by unsetting individual elements.
With Go arrays/slices, you have to actually check against the length of the array, as you wrote:
if i>=0 && i<len(strings) {...}
Personally, I've yet to come across a real life situation that requires doing this - in your example, you could use range(strings)
and stop worrying about indexes.
With maps, which are the Go equivalent of PHP arrays, you can do "isset" by writing:
value, isset := map[index]
if index
is present in the map, value
will be set appropriately and isset
will be true; if not, value
will be set to the zero value of the map's type and isset
will be false.
答案2
得分: 4
len()
应该返回切片的元素数量。
空切片、映射或通道的长度为0。(https://golang.org/ref/spec#Length_and_capacity)
英文:
len()
should return the number of elements of the slice.
> The length of a nil slice, map or channel is 0. (https://golang.org/ref/spec#Length_and_capacity)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论