gpt4 book ai didi

rust - 如何在不移出参数的情况下实现 std::ops:{Add, Sub, Mul, Div} 运算符之一?

转载 作者:行者123 更新时间:2023-11-29 08:12:11 25 4
gpt4 key购买 nike

我正在编写一个光线追踪器,我希望能够减去我的 3D 向量:

use std::ops::Sub;

#[derive(Clone, Debug)]
pub struct Vec3 {
pub v: [f64; 3],
}

impl Sub for Vec3 {
type Output = Vec3;

fn sub(self, other: Vec3) -> Vec3 {
Vec3 {
v: [
self.v[0] - other.v[0],
self.v[1] - other.v[1],
self.v[2] - other.v[2],
],
}
}
}

这似乎有效。但是,当我尝试使用它时:

fn main() {
let x = Vec3 { v: [0., 0., 0.] };
let y = Vec3 { v: [0., 0., 0.] };
let a = x - y;
let b = x - y;
}

我收到编译器的投诉:

error[E0382]: use of moved value: `x`
--> src/main.rs:26:13
|
25 | let a = x - y;
| - value moved here
26 | let b = x - y;
| ^ value used here after move
|
= note: move occurs because `x` has type `Vec3`, which does not implement the `Copy` trait

error[E0382]: use of moved value: `y`
--> src/main.rs:26:17
|
25 | let a = x - y;
| - value moved here
26 | let b = x - y;
| ^ value used here after move
|
= note: move occurs because `y` has type `Vec3`, which does not implement the `Copy` trait

如何编写减法运算符才能使上面的代码正常工作?

请不要告诉我应该使用现有的 3D 数学模块。我确信有更好的东西,但我正在学习如何自己学习这门语言。

How do I implement the Add trait for a reference to a struct?没有帮助,因为它需要为我还没有指定的对象指定生命周期。

最佳答案

在示例中,编译器会告诉您为什么 x 已被移动无效:

   = note: move occurs because `x` has type `Vec3`, which does not implement the `Copy` trait

在这种情况下,您可以简单地添加 #[derive(Copy)] 来赋予 Vec3 复制语义:

#[derive(Clone, Copy, Debug)]
pub struct Vec3 {
pub v: [f64; 3],
}

Copy 是一个标记特征,它向编译器指示类型的值在被移出时不会变得无效。具有此属性的类型被称为具有复制语义,而未实现 Copy 的类型被称为具有移动语义。 Is it possible to make a type only movable and not copyable?How does Rust provide move semantics?更详细地解释这个概念。


但是,您只能为仅包含其他Copy 类型的类型实现Copy。如果 Vec3 实际上在其中包含一个 Vec,编译器将不允许您为它实现 Copy。幸运的是,引用确实实现了 Copy,因此您可以使用以下方法为 reference 实现 SubVec3How do I implement the Add trait for a reference to a struct? 中描述

关于rust - 如何在不移出参数的情况下实现 std::ops:{Add, Sub, Mul, Div} 运算符之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51844745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com