遇到一次 V 恐慌后,V 显示“V 恐慌:数组索引超出范围”错误,用于数组的有效索引

问题描述 投票:0回答:1

有一种新的编程语言,V,由 Alex Medvednikov 创建。我目前使用的是 V 版本 0.1.11。我可以在 V 中声明一个数组,如下所示:

a := [1,2,3]
// Or, mut a := [1,2,3]

我尝试获取该数组的最后一项,例如:

>>> a := [1,2,3]
>>> println(a[-1])
V panic: array index out of range: -1/3
>>> println(a[a.len -1])
V panic: array index out of range: -1/3

每次显示:

V 恐慌:数组索引超出范围:

现在就在这之后,如果我尝试从数组中获取项目,那么它仍然显示相同的错误:

>>> println(a[1])
V panic: array index out of range: -1/3
>>> println(a.len)
V panic: array index out of range: -1/3

然而,如果我们在遇到

V panic
之前尝试从数组中获取项目,它会打印出相同的内容而不会出现任何错误,就像终端中的一个新实例一样:

>>> a := [1,2,3]
>>> println(a.len)
3
>>> println(a[1])
2

为什么在我们事先遇到

V panic
后,V_ 每次都会显示
V panic
表示有效索引?

arrays vlang
1个回答
2
投票

这可能是 V REPL 中的一个错误。您可以在此处提交问题

与 Python 不同,V-lang 没有从具有负索引的数组末尾获取元素的功能

a := [1,2,3]
a[-1] //isn't valid

官方文档简短而准确

mut nums := [1, 2, 3]
println(nums) // "[1, 2, 3]"
println(nums[1]) // "2" 

nums << 4
println(nums) // "[1, 2, 3, 4]"


nums << [5, 6, 7]
println(nums) // "[1, 2, 3, 4, 5, 6, 7]"

mut names := ['John']
names << 'Peter' 
names << 'Sam' 
// names << 10  <-- This will not compile. `names` is an array of strings. 
println(names.len) // "3" 
println('Alex' in names) // "false" 

// We can also preallocate a certain amount of elements. 
nr_ids := 50
ids := [0 ; nr_ids] // This creates an array with 50 zeroes 

 //....
© www.soinside.com 2019 - 2024. All rights reserved.