在原始人is about slices上进行的沙沙练习之一.
当我试图解决这个练习时,我首先使用[start...end]
语法将一个片段放入给定的数组中
fn slice_out_of_array() {
let a: [u8; 5] = [1, 2, 3, 4, 5];
let nice_slice = a[1..4];
assert_eq!([2, 3, 4], nice_slice)
}
编译器抱怨并告诉我:
error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
--> exercises/primitive_types/primitive_types4.rs:10:9
|
10 | let nice_slice = a[1..4];
| ^^^^^^^^^^ doesn't have a size known at compile-time
|
= help: the trait `Sized` is not implemented for `[u8]`
= note: all local variables must have a statically known size
= help: unsized locals are gated as an unstable feature
help: consider borrowing here
|
10 | let nice_slice = &a[1..4];
| +
error: aborting due to previous error
For more information about this error, try `rustc --explain E0277`.
跑rustc --explain E0277
分并不能真正回答我的问题.它解释了当函数指定应该实现特征时,参数不实现特征意味着什么.这对我来说是清楚的,但我不完全清楚这里出了什么问题.
这就是我正在发生的事情,但我想听听别人的意见.
-
编译器无法从Slice语法计算出结果片有多大,因此它无法在堆栈上分配适当的空间.
-
默认情况下,片是基本类型,驻留在堆栈而不是堆上.
-
如果我接受建议并添加
&
,编译器将在堆栈上推送对堆栈上已有的原始数组的引用--该引用具有已知的大小.这就解决了问题.
这样对吗?有没有这样一种情况,我可以取一片而不加&
符号?