如何在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屋!