Reputation: 3047
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 ?
Upvotes: 0
Views: 81
Reputation: 9647
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.
Upvotes: 1