为什么 [u8] 没有实现 Clone?

Gue*_*OCs 1 rust

下面的例子仅仅是一个例子,我知道我不需要克隆这个工作,但如果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

Pet*_*all 5

那为什么不是[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,也就是说,因为我们不知道它将有多少个元素,所以我们无法在编译时知道它的大小。但是从这个方法返回它意味着它被移到堆栈上,如果编译器不知道为它留下多少空间,这是不可能的。