Why I must use `&T` instead of `T` when returning impl trait?

Viewed 132

I want to know why the first way fails. As far as I know, T is a generic parameter, which can take a reference value; why I must use &T instead of T?

fn test() -> impl std::fmt::Debug + 'static {
    let value1 = "v".to_string();
    make_debug(&value1)
}

// 1. This one not works well
fn make_debug<T: std::fmt::Debug>(_: T) -> impl std::fmt::Debug {
    42u8
}

// 2. This one works well
// fn make_debug<'a, T: std::fmt::Debug>(_: &'a T) -> impl std::fmt::Debug {
//     42u8
// }

// 3. This one works well
//fn make_debug<T: std::fmt::Debug>(_: T) -> u8 {
//    42u8
//}

fn main() {
    test();
}
error[E0515]: cannot return value referencing local variable `value1`
 --> src/main.rs:3:5
  |
3 |     make_debug(&value1)
  |     ^^^^^^^^^^^-------^
  |     |          |
  |     |          `value1` is borrowed here
  |     returns a value referencing data owned by the current function
0 Answers
Related