How can I overload the assignment operation in Rust?
Asked Answered
M

1

14

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.

Modesta answered 22/5, 2016 at 17:15 Comment(0)
H
17

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

Hindi answered 13/3, 2017 at 12:51 Comment(1)
I realized, my understanding of Rust assignment was wrong, as I said in my question, I came in Rust with C++ back. (that most of the time makes confusion.)Modesta

© 2022 - 2024 — McMap. All rights reserved.