为什么会出现错误E0277:在编译时无法知道类型[[{integer}]`的值的大小?

时间:2018-11-10 05:58:45

标签: rust

在以下代码中,我得到了错误:

error[E0277]: the size for values of type `[{integer}]` cannot be
known at compilation time at the line `for n in numbers[1..] {`

我四处搜寻,但一无所获。

fn main() {
    let mut numbers = Vec::new();
    numbers.push(1);
    numbers.push(32);
    numbers.push(43);
    numbers.push(42);
    // ... And many more
    println!("{:?}", numbers); // Sanity

    let mut sum = 0;

    // Problem code area
    for n in numbers[1..] {
        sum = sum + n;
    } 
    // Problem code area

    println!("{}", sum);
}

此外,如果我将问题行替换为以下内容(添加&*以进行所有权/借用和取消引用),问题行会起作用

for n in &numbers[1..] {
    sum = sum + *n;
}

为什么编译会以以前的方式失败?

1 个答案:

答案 0 :(得分:3)

numbers[1..]没有大小,因为它只有numbers的¹slice。切片只能在某种指针后面使用,例如&[T]Box<[T]>Arc<[T]>。以下问题具有有关切片的更多信息:

由于[T]的大小不正确,因此无法实现IntoIterator,这是用于在for循环中迭代事物的特征。 (请参见Why can I iterate over a slice twice, but not a vector?IntoIterator::into_iter具有以下原型:

fn into_iter(self) -> Self::IntoIter;

Self不能为未定大小的类型,因为into_iter按值取self

&numbers[1..]是一个引用(类型&[T]),它既有大小,又实现了IntoIterator,因此工作正常。

full compiler output还给出了有关IntoIterator的错误消息,并建议使用numbers[1..].iter()代替。由于.iter()占用&self,因此可以在未调整大小的类型上调用它,因此这是解决问题的另一种方法。


¹在许多地方,包括官方文档,无限定的术语“切片”用于指代引用类型&[T]。我称numbers[1..]切片,因为它不是参考。其类型仅为[T]