【问题标题】:Why does cloning my custom type result in &T instead of T?为什么克隆我的自定义类型会导致 &T 而不是 T?
【发布时间】:2016-10-12 10:41:36
【问题描述】:
use generic_array::*; // 0.12.3
use num::{Float, Zero}; // 0.2.0

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

impl<T, N: ArrayLength<T>> Vector<T, N>
where
    T: Float + Zero,
{
    fn dot(&self, other: Self) -> T {
        self.data
            .iter()
            .zip(other.data.iter())
            .fold(T::zero(), |acc, x| acc + *x.0 * *x.1)
    }

    fn length_sq(&self) -> T {
        self.dot(self.clone())
    }
}
error[E0308]: mismatched types
  --> src/lib.rs:21:18
   |
21 |         self.dot(self.clone())
   |                  ^^^^^^^^^^^^ expected struct `Vector`, found reference
   |
   = note: expected type `Vector<T, N>`
              found type `&Vector<T, N>`

为什么会这样?为什么clone 返回&amp;T 而不是T

如果我自己实现Clone,为什么这会起作用?

use generic_array::*; // 0.12.3
use num::{Float, Zero}; // 0.2.0

#[derive(Debug)]
struct Vector<T, N: ArrayLength<T>> {
    data: GenericArray<T, N>,
}

impl<T: Float, N: ArrayLength<T>> Clone for Vector<T, N> {
    fn clone(&self) -> Self {
        Vector::<T, N> {
            data: self.data.clone(),
        }
    }
}

impl<T, N: ArrayLength<T>> Vector<T, N>
where
    T: Float + Zero,
{
    fn dot(&self, other: Self) -> T {
        self.data
            .iter()
            .zip(other.data.iter())
            .fold(T::zero(), |acc, x| acc + *x.0 * *x.1)
    }

    fn length_sq(&self) -> T {
        self.dot(self.clone())
    }
}

【问题讨论】:

    标签: reference rust cloning


    【解决方案1】:

    当您的类型未实现 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`
    

    这是由于自动引用规则:编译器看到Example 没有实现Clone,因此它尝试在&amp;Example 上使用Clone,并且不可变引用总是实现Clone .

    您的Vector 类型没有实现Clone 的原因是the derived Clone implementation doesn't have the right bounds on the type parameters (Rust issue #26925)。尝试显式编写 self.dot(Self::clone(self)) 以获取类似这些行的错误消息。

    另见:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-19
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      相关资源
      最近更新 更多