How to clone a borrowed content?

#[derive(Clone)]
struct T {...}
impl XX for Vec<T>{
fn foo(&mut self, v: &T) {
  self.push(v.clone());
}
}

Apparently the push clone line would not work. But I could not figure out how to make it work. I do not want to specify any lifetime, so I do not use &T in Vec.

Is T in you code an abstract type? Abstract types don’t support any operations at all, and ignore all implementations they actually have, except the ones that you explicitly require them to support. So clone on abstract type won’t work until you say T: Clone.

struct T { ... } is not very idiomatic since T is the de facto name of a type parameter:

// the whole impl block is generic over some abstract type T
impl<T> XX for Vec<T> {
    fn foo (...) -> ..
    where
        T : Clone, // this function/method requires that T be Clone
    {
        // ...
    }
}

But given your struct T { ... }, it does not seem to be a type parameter but an actual concrete type.

In that case, #[derive(Clone)] should do the trick, unless one of the fields of the struct is not Clone.
This is problematic with #[derive(Clone)], since it is not very smart… For instance, even if *const T is Copy and thus Clone for all T, the following struct is only Clone when T : Clone:

#[derive(Clone)]
struct Ptr<T> /* = */ (
    *const T,
);

This happens because most often that not such T : Clone bound is required:

#[derive(Clone)] // Foo<T> is Clone only when T is Clone
struct Foo<T> /* = */ (
    T,
);

impl<T> XX for Vec< Foo<T> > {
    fn foo (...) -> ..
    where
        T : Clone, // thanks to the derive, this bound implies that Foo<T> is Clone
    {
        ...
    }
}

Sorry, it is persudo code, T is not abstract type.

I may have understood you wrong. I do not think you descripted (after But) the problem I have. I have all things Clone-able.

Problem is that, v.clone() returns &T while XX requires T. And *v.clone() fails with moving borrowed content.

If v.clone(): &T, then most probably v: &&T, thus you need (*v).clone()

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.