Clone value of reference variable Not working

#![allow(warnings)]

use std::{
    ops::{Deref, DerefMut}
};


struct Example<T>(&'static str, T);

impl<T> Deref for Example<T> {
    type Target = T;
    fn deref(&self) -> &Self::Target {
        &self.1
    }
}

impl<T> DerefMut for Example<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.1
    }
}

impl<T> Example<T> {
    fn get(&self) -> T {
        self.1
    }
}

fn main() {
    let mut example = Example::<String>("Albert", String::from("000-000"));
    println!("{}", example.get());
}

(Playground)

move occurs because `self.1` has type `T`, which does not implement the `Copy` trait

How can I get value T from get() function? It can't return &T, should return T

In general case there's no way.

If you can restrict types on which get can be called, you'll be able to clone explicitly:

impl<T> Example<T> {
    fn get(&self) -> T where T: Clone {
        self.1.clone()
    }
}

I can restrict types for struct Example or implementation.
But in case the restricted types don't have clone() function, is there other way to get values?

No. If some type doesn't implement Clone, it is single-ownership only. So, while your Example<T> is still alive, you can't get T out of it.
There are two possible workarounds, but they both change semantics of the code:

  • Store an Option<T> inside Example<T> and call Option::take inside get.
  • Make get take self instead of &self.

Sounds good! If possible ,can you write an example in playground and share it with me?
Thanks

Here's 3 examples in the playground, each of them with pros and cons Rust Playground

2 Likes