How to convert `& T` only to` T`?

I want to write a function that takes an array with any type in it and returns the last element of the array, so I tried:

fn main() {
    let v = ["a", "b"];
    println!("{}", last(&v));
}

fn last<T: Clone>(slice: &[T]) -> &T {
    &slice[slice.len()-1]
}

and this works, but when I apply a little tweak:

fn main() {
    let v = ["a", "b"];
    println!("{}", last(&v));
}

fn last<T: Clone>(slice: &[T]) -> T {
    &slice[slice.len()-1]
}

Then they met me:

error[E0308]: mismatched types
 --> <anon>:9:5
  |
9 |     &slice[n-1]
  |     ^^^^^^^^^^^ expected type parameter, found &T
  |
 = note: expected type `T`
            found type `&T`

How to convert &Tto simple T?

+6
source share
1 answer

In the first example, you return &Tand reference something, so the value and types correspond to:

fn last<T: Clone>(slice: &[T]) -> &T {
//                                ^^
    &slice[slice.len()-1]
//  ^
}

But, then you said that you were no longer going to return the link, but did not change the implementation.

fn last<T: Clone>(slice: &[T]) -> T {
//                                ^
    &slice[slice.len()-1]
//  ^
}

T, &Tand &mut Tall different types from each other! This means that this is the same as this “little setup”:

fn foo() -> i32  { 42 } // Before
fn foo() -> bool { 42 } // After

& :

fn last<T: Clone>(slice: &[T]) -> T {
    slice[slice.len()-1]
}

...

error[E0507]: cannot move out of indexed content
 --> src/main.rs:4:9
  |
4 |         slice[slice.len()-1]
  |         ^^^^^^^^^^^^^^^^^^^^ cannot move out of indexed content

" " ? ?.


: . :

  • Copy, :

    fn last_copy<T: Copy>(slice: &[T]) -> T {
        slice[slice.len()-1]
    }
    
  • Clone, Clone, :

    fn last_clone<T: Clone>(slice: &[T]) -> T {
        slice[slice.len()-1].clone()
    }
    

    , - .

  • . , , . .

+8

All Articles