gpt4 book ai didi

copy - 按值重载运算符会导致使用移动的值

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

编译以下使用运算符重载的 Rust 代码

use std::ops::{Add};

#[derive(Show)]
struct Point {
x: int,
y: int
}

impl Add for Point {
type Output = Point;

fn add(self, other: Point) -> Point {
Point {x: self.x + other.x, y: self.y + other.y}
}
}

fn main() {
let p: Point = Point {x: 1, y: 0};
let pp = p + p;
}

由于 p 的所有权导致编译器错误:

<anon>:21:18: 21:19 error: use of moved value: `p`
<anon>:21 let pp = p + p;
^
<anon>:21:14: 21:15 note: `p` moved here because it has type `Point`, which is non-copyable
<anon>:21 let pp = p + p;
^

解释其背后的基本原理here并导致RFC未被接受(部分原因是上述示例)。然而,后来以下RFC仍然为运算符引入了按值类型签名。

虽然我理解该决定背后的理由。由于我缺乏使用rust 经验,我不确定允许上述代码工作的“正确”方法是什么(a)如果我不想复制或(b)如何使结构可复制?

最佳答案

如果您不想复制,就我的新手理解而言,您需要在对 Point 的引用上实现 Add

这将得到 RFC 的支持:

Fortunately, there is no loss in expressiveness, since you can always implement the trait on reference types. However, for types that do need to be taken by reference, there is a slight loss in ergonomics since you may need to explicitly borrow the operands with &. The upside is that the ownership semantics become clearer: they more closely resemble normal function arguments.

确实它似乎有效:

use std::ops::{Add};

#[derive(Show)]
struct Point {
x: i32,
y: i32
}

impl<'a> Add for &'a Point {
type Output = Point;

fn add(self, other: &'a Point) -> Point { //'
Point {x: self.x + other.x, y: self.y + other.y}
}
}

fn main() {
let p: Point = Point {x: 1, y: 0};
let pp = &p + &p;
println!("{:?}", pp);
}

( playpen )

要使 Point 可复制,只需将 #[derive(Show)] 替换为 #[derive(Show,Copy)]。这些结构过去默认是可复制的,但它 changed .

关于copy - 按值重载运算符会导致使用移动的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27856991/

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