Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

string - How do I make format! return a &str from a conditional expression?

I happened upon this problem where format! creates a temporary value in a pattern that is not anchored to anything, as far as I understand it.

let x = 42;
let category = match x {
    0...9 => "Between 0 and 9",
    number @ 10 => format!("It's a {}!", number).as_str(),
    _ if x < 0 => "Negative",
    _ => "Something else",
};

println!("{}", category);

In this code, the type of category is a &str, which is satisfied by returning a literal like "Between 0 and 9". If I want to format the matched value to a slice using as_str(), then I get an error:

error[E0716]: temporary value dropped while borrowed
 --> src/main.rs:5:24
  |
3 |     let category = match x {
  |         -------- borrow later stored here
4 |         0...9 => "Between 0 and 9",
5 |         number @ 10 => format!("It's a {}!", number).as_str(),
  |                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        - temporary value is freed at the end of this statement
  |                        |
  |                        creates a temporary which is freed while still in use
  |
  = note: consider using a `let` binding to create a longer lived value
  = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

I have done some reading, and found people with similar problems, but I couldn't seem to find any solution.

A simple workaround would be to have category be a String instead of a &str, but I don't like the idea of having to put .to_string() on the end of every literal in the pattern, as it's not as clean.

Is there a way to solve the problem, or do I just need to work around it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is 90% a duplicate of Return local String as a slice (&str), see that for multiple other solutions.

There's one extra possibility since this is all in one function: You can declare a variable for the String and only set it when you need to allocate. The compiler (obliquely) suggests this:

consider using a let binding to create a longer lived value

fn main() {
    let x = 42;
    let tmp;

    let category = match x {
        0...9 => "Between 0 and 9",
        number @ 10 => {
            tmp = format!("It's a {}!", number);
            &tmp
        }
        _ if x < 0 => "Negative",
        _ => "Something else",
    };

    println!("{}", category);
}

This is mostly the same as using a Cow, just handled by the compiler instead of a specific type.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...