Why does cloning my custom type result in &T instead of T?

前端 未结 1 1165
别那么骄傲
别那么骄傲 2020-12-11 04:56
use generic_array::*; // 0.12.3
use num::{Float, Zero}; // 0.2.0

#[derive(Clone, Debug)]
struct Vector> {
    data: GenericArray<         


        
相关标签:
1条回答
  • 2020-12-11 05:37

    You get this error when your type doesn't implement Clone:

    struct Example;
    
    fn by_value(_: Example) {}
    
    fn by_reference(v: &Example) {
        by_value(v.clone())
    }
    
    error[E0308]: mismatched types
     --> src/lib.rs:6:14
      |
    6 |     by_value(v.clone())
      |              ^^^^^^^^^ expected struct `Example`, found &Example
      |
      = note: expected type `Example`
                 found type `&Example`
    

    This is due to the auto-referencing rules: the compiler sees that Example doesn't implement Clone, so it instead tries to use Clone on &Example, and immutable references always implement Clone.

    The reason your Vector type doesn't implement Clone is because the derived Clone implementation doesn't have the right bounds on the type parameters (Rust issue #26925). Try explicitly writing self.dot(Self::clone(self)) to get an error message along these lines.

    See also:

    • Deriving a trait results in unexpected compiler error, but the manual implementation works
    0 讨论(0)
提交回复
热议问题