0

I´m following the rust's reference book and in the chapter 10.3. Validating References with Lifetimes I'm playing with various values and ways to wrasp the concepts rigth. But i can't found a solution to return an &str with a diferent lifetime for the longestv2 function:

fn main() {
    let result:&str;
    let result2:&str;
    {
        let string1 = String::from("long string is long");
        {
    
            let string2 = String::from("xyz");
            result = longestv1(string1.as_str(), string2.as_str());
            result2= longestv2(string1.as_str(), string2.as_str());
        }
    }
    println!("The longestv1 string is {}", result);
    println!("The longestv2 string is {}", result2);
}


fn longestv1<'a,'b>(x: &'a str, y: &'a str) ->  &'b str {
    if x.len() > y.len() {        
        "x"
    } else {
        "y"
    }
}

fn longestv2<'a,'b>(x: &'a str, y: &'a str) ->  &'b str {
    if x.len() > y.len() {
        format!("{} with {}",x, x.len()).as_str()
    } else {
        format!("{} with {}",y, y.len()).as_str()
    }
}

It will give me this errors:

error[E0515]: cannot return reference to temporary value
  --> src\main.rs:31:9
   |
31 |         format!("{} with {}",x, x.len()).as_str()
   |         --------------------------------^^^^^^^^^
   |         |
   |         returns a reference to data owned by the current function
   |         temporary value created here

error[E0515]: cannot return reference to temporary value
  --> src\main.rs:33:9
   |
33 |         format!("{} with {}",y, y.len()).as_str()
   |         --------------------------------^^^^^^^^^
   |         |
   |         returns a reference to data owned by the current function
   |         temporary value created here

I want to return an &str like the first function longestv1, I know that String works but i want to wrasp the concepts

I tried to wrap and Option and then use as_ref() and other things in the web, copy() ,clone() , into() etc... but nothing trick rust to move out the temporaly value

waldo
  • 1

1 Answers1

3

TL;DR: You cannot.


You cannot return a reference to a temporary. Period. You can leak it, but don't.

The compiler will free your String at the end of the function, and then you'll have a dangling reference. This is bad.

Just return String.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
  • there most be a way to return a &str as the first example? to make it permanent, not temporary. I have my c++ background on pointers and that stuff but really scraching my brain on this – waldo Apr 03 '22 at 10:02
  • 2
    The first function doesn't create a `String`. But `String` allocates and needs someone to free this allocation. In C++, this is like returning `std::string_view` from a function that references a `std::string` inside this function. It will not error, but be UB at runtime. In Rust it errors, which is better. – Chayim Friedman Apr 03 '22 at 10:04