Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Rust's Box<T> Clone implementation requires T to be Clone?

Tags:

rust

I was writing a library for a generic Box<T> and on one part of the code I needed to clone the Box<T>, so I did something like this:

impl<T> OnTheFlySwap<T>
where
    T: ?Sized + Send + Sync, Box<T>: Clone
{ 

I added Box<T>: Clone thinking this is not a big deal, because only objects that explicitly prohibits Box<T>: Clone would have a problem. But no, apparently if the object does not explicitly implements Box<T>: Clone then I have a problem, because this is the official impl Clone for Box:

impl<T, A> Clone for Box<T, A> where
    T: Clone,
    A: Allocator + Clone, 

It requires T to be Clone. Why? Wouldn't every Box<T> be Clone, since cloning a Box requires no time? If an object does not want its box to be clone then it could implement !Clone for it, but the default should be impl Clone for Box<T> for any T.

like image 800
Guerlando OCs Avatar asked Sep 11 '25 01:09

Guerlando OCs


1 Answers

A Box<T> in Rust represents a box which owns a T. If you could clone a Box and get a second box pointing to the same T, then which one would own the T value? Box isn't just Rust's version of C++ pointers; it represents a concept of ownership that a language like C++ doesn't enforce.

As an exercise, consider trying to write the function you're suggesting for Box::clone yourself. Its signature would be

fn my_clone<T>(value: &Box<T>) -> Box<T> { ... }

Try writing a function with that signature without dipping into unsafe. The compiler will let you know pretty quickly what went wrong.

The only safe way to clone a box is to clone everything inside of the box as well, and that requires T : Clone.

like image 197
Silvio Mayolo Avatar answered Sep 13 '25 18:09

Silvio Mayolo