Why does the resulting clone () method return a link?

Obtaining a sign Clonefor a structure containing a reference to an object of a generic type (if it is not associated with Clone. In this case, cloning works as expected) generates a method clone()that returns a reference to the object, but not a new object.

I have a code:

#[derive(Clone)]
struct A<'a, T: 'a>{
    ref_generic: &'a T
}

fn test_call<'a, T: 'a>(a: &A<'a, T>)->A<'a, T>{
    a.clone()
}

This will result in an error:

error[E0308]: mismatched types
  --> src/lib.rs:15:5
   |
14 | fn test_call<'a, T: 'a>(a: &A<'a, T>)->A<'a, T>{
   |                                        -------- expected `A<'a, T>` because of return type
15 |     a.clone()
   |     ^^^^^^^^^ expected struct `A`, found &A<'_, T>
   |
   = note: expected type `A<'a, T>`
              found type `&A<'_, T>`

Why is this behavior happening this way?

After manual implementation, this obstacle can be avoided, but unpleasantly.

impl<'a, T: 'a> Clone for A<'a, T>{
    fn clone(&self)->Self{
        A{ref_generic: self.ref_generic}
    }
}
+4
source share
1 answer

You do not call A::clone(). You call &A::clone(), i.e. You are cloning a link, not an object.

A::clone(), (Clone::clone &self, ref , , ref ), . ( , , , (*a).clone() .) , Clone :

impl <'a, T: Clone + 'a> Clone for A<'a, T> {
  fn clone(&self) -> Self { Self { ref_generic: self.ref_generic } }
}

Clone T. , - . # 26925.

test_call T, , Clone impl A , Clone impl, , &A.

+5

Source: https://habr.com/ru/post/1688065/


All Articles