Golang 数组下标判断:如何检查下标是否越界
在 Golang 中,可以通过数组的下标来访问数组中的元素,但如果要判断某个下标是否存在,需要先判断下标是否越界。
判断数组下标是否越界可以使用以下方式:
- 使用
len函数获取数组长度,判断下标是否小于数组长度:
arr := [5]int{1, 2, 3, 4, 5}
index := 3
if index < len(arr) {
fmt.Println(arr[index])
} else {
fmt.Println('index out of range')
}
- 使用
for range遍历数组,判断下标是否在范围内:
arr := [5]int{1, 2, 3, 4, 5}
index := 3
found := false
for i, v := range arr {
if i == index {
fmt.Println(v)
found = true
break
}
}
if !found {
fmt.Println('index not found')
}
在以上两种方式中,如果下标越界,可以通过 else 或 found 变量来判断下标是否存在。
原文地址: https://www.cveoy.top/t/topic/lDLn 著作权归作者所有。请勿转载和采集!