如何在 Rust 中重载赋值操作? [英] How can I overload the assignment operation in Rust?
问题描述
std::ops
,但没有什么可用于简单的赋值.
There are lots of operations in std::ops
, but there is nothing for a simple assignment.
我来自 C++ 背景,那里有复制构造函数和赋值运算符重载为您完成工作.我在 Rust 中需要类似的东西.
I'm coming from a C++ background, where there are copy constructor and assignment operator overloading that do the work for you. I need something like that in Rust.
推荐答案
你不能重载赋值.将变量从一个位置移动到另一个位置是 Rust 所有权语义的核心组成部分,并且是不可覆盖的.
You cannot overload assignment. Moving a variable from one location to another is a core component of Rust's ownership semantics and is not overridable.
另一个答案建议您自定义实现 Copy
特性.这是没有意义的,因为没有什么可实现的:
Another answer suggests that you custom-implement the Copy
trait. This makes no sense, as there's nothing to implement:
pub trait Copy: Clone { }
你可以实现Clone
对于一个类型,但要使用 clone
你必须显式调用它:
You could implement Clone
for a type, but to use clone
you have to call it explicitly:
let foo = bar.clone();
实际赋值仍然只是将位从右侧复制到左侧,唯一的区别是您没有放弃对 bar的所有权代码>.
The actual assignment is still just copying bits from the right-hand side to the left-hand side, the only difference is that you don't give up ownership of bar
.
如果您的类型可以通过简单地复制位来复制,那么实现Copy
是合适的.如果可以通过执行某种函数来复制它,那么实现Clone
是合适的.我不知道在任何给定的类型分配中隐式执行代码(我认为这是一件好事).
If your type can be duplicated by simply copying bits, then it's appropriate to implement Copy
. If it can be duplicated by executing some kind of function, then it's appropriate to implement Clone
. There is no way I know of to implicitly execute code at any given assignment of a type (and I count that as a good thing).
这篇关于如何在 Rust 中重载赋值操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!