Search code examples
structrustmove-semanticspass-by-value

Copy a struct to pass to a function - this field does not implement `Copy`


Here is my struct:

#[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>,
}

I am trying to pass my struct to multiple functions.

Here is my error:

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`

Solution

  • If a type implements Copy, "copies happen implicitly", i.e. you do not have to explicitly state that you want to copy the value. Because Vec implements Drop, it can not implement Copy, preventing you from accidentally copying values around without noticing it.

    Thus, Vec only implements Clone (if the contained type implements Clone), so that you can explicitly copy a vector by calling Clone.

    Similarly, you should think twice if ArimaModel should really derive Copy or if you actually want to derive Clone so that you have to explicitly state that you want a copy.

    But if you just want to pass ArimaModel into different functions, you might want to borrow them (i.e. pass &ArimaModel or &mut ArimaModel instead of ArimaModel).