I want to convert a number to a string. Sometimes, the number doesn't exist, and it should be represented by an empty string.
I tried to write the following code:
struct Example {
number: Option<usize>,
}
impl Example {
fn example(&self) {
let result = match self.number {
Some(num) => num.to_string().as_str(),
None => "",
};
}
}
fn main() {}
However, the borrow checker doesn't allow this:
error[E0597]: borrowed value does not live long enough
--> src/main.rs:8:49
|
8 | Some(num) => num.to_string().as_str(),
| --------------- ^ temporary value dropped here while still borrowed
| |
| temporary value created here
...
11 | }
| - temporary value needs to live until here
How can I write this correctly/idiomatically?