3

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
  • when you call make_debug(&value1) you are borrowing the value1 but the signature of the function requires a T which consumes the value, if you remove the ampersand```make_debug(value1)``` it should work but be aware, you consume the objecte which means you cant use it afterwards – VictorJimenez99 May 11 '21 at 14:01
  • This appears to be a duplicate of [“borrowed value does not live long enough” with a generic function that returns impl trait](https://stackoverflow.com/q/57976042/155423) / [Impl trait with generic associated type in return position causes lifetime error](https://stackoverflow.com/q/56636442/155423). – Shepmaster May 11 '21 at 14:03
  • See also: [impl Trait capturing lifetime of type parameter](https://github.com/rust-lang/rust/issues/79415) and [Unclear compiler error when impl Trait return value captures non-'static argument](https://github.com/rust-lang/rust/issues/82171). – Masklinn May 11 '21 at 14:04
  • 1
    @Netwave I have seen https://github.com/pretzelhammer/rust-blog/blob/master/posts/common-rust-lifetime-misconceptions.md#1-t-only-contains-owned-types. `T is a superset of both &T and &mut T` – boundless-forest May 11 '21 at 14:10

0 Answers0