0
fn main() {
    let s = String::new().as_str();
    println!("{}", s);
}

I had a problem with my program above:

temporary value is freed at the end of this statement

This happens when I create a String but only need its reference. I understand the compiler error and the suggested fix. But creating a temporary binding by hand is ugly. I am asking here to see whether Rust has language support to extend the lifetime of an owned value whose borrowed reference is still kept in use, without programmer writing a temporary binding by hand.

I was imagining something like this:

let s = (String::new())@.as_str();

The @ symbol creates an anonymous binding as if the programmer creates it by hand. It is anonymous because it is not being used directly and so doesn't have to pollute the current namespace. This isn't valid Rust yet, but I'd like to know if I can do the same using what Rust already provides, for example, macros.

Discussion on rust-lang.org

TSK
  • 509
  • 1
  • 9

1 Answers1

2

In a way this is possible, just don't pass the temporary value into a function immediately:

let s: &str = &String::new();

will create a hidden temporary value. Your code doesn't work because the temporary created gets passed to as_str immediately and thus only lives for the expression.

For reference: Why is it legal to borrow a temporary?

cafce25
  • 15,907
  • 4
  • 25
  • 31
  • This answer only works in the special case of `String`. For example, it fails with `PathBuf`: `let s = std::path::PathBuf::new().to_str().unwrap();` There is no easy way to create a hidden temporary value. – TSK Jan 04 '23 at 09:53
  • @TSK I specifically mention you can't immediately pass it to a function which `to_str` will do... there is your problem. – cafce25 Jan 05 '23 at 19:02