为什么克隆我的自定义类型会导致 &T 而不是 T? [英] Why does cloning my custom type result in &T instead of T?

查看:12
本文介绍了为什么克隆我的自定义类型会导致 &T 而不是 T?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 返回 &T 而不是 T?

Why does this happen? Why does clone return &T instead of T?

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

Why does this work if I implement Clone myself?

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())
    }
}

推荐答案

当您的类型没有实现 Clone 时,您会收到此错误:

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`

这是由于自动引用规则:编译器看到Example没有实现Clone,所以它尝试使用Clonecode> on &Examp;Example,不可变引用总是实现Clone.

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.

你的 Vector 类型没有实现 Clone 的原因是因为 派生的 Clone 实现在类型参数上没有正确的界限(Rust 问题 #26925).尝试显式编写 self.dot(Self::clone(self)) 以获取沿着这些行的错误消息.

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.

另见:

这篇关于为什么克隆我的自定义类型会导致 &amp;T 而不是 T?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆