Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to implement value-like semantics for non-trivial types in rust

I would like to write a type that has an implementation for the Drop trait. but I would like to not need to call .clone() every time I need a copy like a type that implement Copy. But from what I understood, I cannot use the Copy trait because it can only be implemented for trivial types that can be memcpyed around and is incompatible with the Drop trait.

for example:

use std::rc::Rc;

#[derive(Clone)]
struct Impl {
    //... details
}

#[derive(Clone)]
struct ValueLikeHandle {
    handle : Rc<Impl>
}

impl ValueLikeHandle {
    pub fn new() -> ValueLikeHandle {
        ValueLikeHandle { handle : Rc::new(Impl{}) }
    }
}

fn main() {
    let a = ValueLikeHandle::new();
    let b = a; // I would like this to be a .clone() with out writing it.
    let c = a;
}

How can I implement value semantics for a non-trivial type ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To the best of my knowledge you can’t. This is a conscious design decision to prevent gotchas.

Clone has the potential to be expensive and therefore shouldn’t happen implicitly. Also, it would be a gotcha because assignment either uses move semantics for non-copy types and copy semantics for copy types, but never clones.

In some languages you could overload the assignment operator to implement clone semantics, but Rust doesn’t allow that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading