下面的例子仅仅是一个例子,我知道我不需要克隆这个工作,但如果S
用枚举[T]
和Vec<T>
,我想调整的载体,T
必须是Clone
。
struct S<'a, T>{
a: &'a [T]
}
impl<'a, T> S<'a, T> {
pub fn borrow(&self) -> &[T]
where [T]: Clone {
self.a
}
}
fn main() {
let slice:[u8;3] = [1,2,3];
let x = S{a: &slice};
x.borrow();
}
Run Code Online (Sandbox Code Playgroud)
错误:
error[E0277]: the trait bound `[u8]: Clone` is not satisfied
--> src/main.rs:17:7
|
17 | x.borrow();
| ^^^^^^ the trait `Clone` is not implemented for `[u8]`
Run Code Online (Sandbox Code Playgroud)
那么,为什么不是[u8]
Clone
?
那为什么不是
[u8]
Clone
?
查看clone
定义中方法的类型Clone
:
pub trait Clone {
pub fn clone(&self) -> Self;
// more stuff omitted..
}
Run Code Online (Sandbox Code Playgroud)
它返回Self
,[u8]
在这种情况下就是这样。问题是[u8]
不是Sized
,也就是说,因为我们不知道它将有多少个元素,所以我们无法在编译时知道它的大小。但是从这个方法返回它意味着它被移到堆栈上,如果编译器不知道为它留下多少空间,这是不可能的。
归档时间: |
|
查看次数: |
91 次 |
最近记录: |