Clone value of reference variable Not working


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 {

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 {

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


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 {

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?

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


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.