How can I overload the assignment operation in Rust?

谁说胖子不能爱 提交于 2019-12-14 03:45:44

问题


There are lots of operations in std::ops, but there is nothing for a simple assignment.

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.


回答1:


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.

Another answer suggests that you custom-implement the Copy trait. This makes no sense, as there's nothing to implement:

pub trait Copy: Clone { }

You could implement Clone for a type, but to use clone you have to call it explicitly:

let foo = bar.clone();

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.


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).




回答2:


WRONG ANSWER

As I said, I was confused :D. The answer to my question is to derive the Copy and Clone traits. I just have to add

#[derive(Clone, Copy)]

above my type definition; that way I can get my desired functionality.

For a customized logic of assigning and copying, you can easily implement Copy and Clone yourself, instead of using derivation.



来源:https://stackoverflow.com/questions/37377250/how-can-i-overload-the-assignment-operation-in-rust

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!