复制结构以传递给函数-该字段未实现`Copy`

时间:2019-01-13 10:32:18

标签: struct rust move-semantics pass-by-value

这是我的结构:

#[derive(Copy, Clone)]
pub struct ArimaModel {
    p: u8,
    d: u8,
    q: u8,
    holdout_length: u16,
    max_ar_lag: u8,
    max_ma_lag: u8,
    df_lags: u8,
    time_series: Vec<f64>,
    ar_lags: Vec<usize>,
}

我正在尝试将结构传递给多个函数。

这是我的错误:

error[E0204]: the trait `Copy` may not be implemented for this type
  --> src/lib.rs:1:10
   |
1  | #[derive(Copy, Clone)]
   |          ^^^^
...
10 |     time_series: Vec<f64>,
   |     --------------------- this field does not implement `Copy`
11 |     ar_lags: Vec<usize>,
   |     ------------------- this field does not implement `Copy`

1 个答案:

答案 0 :(得分:1)

如果类型实现index.Rmd"copies happen implicitly",即您不必明确声明要复制该值。因为Copy实现了Vec,所以它无法实现Drop,从而防止您在不注意的情况下意外地复制值。

因此,Copy仅实现Vec(如果所包含的类型实现了Clone),因此您可以通过调用Clone显式复制向量。

类似地,如果Clone应该真正派生ArimaModel还是您真的想派生Copy,则您应该三思而后行,以便您必须明确声明要复制。

但是,如果您只是想将Clone传递给不同的函数,则可能想借用它们(即,传递ArimaModel&ArimaModel而不是&mut ArimaModel)。