3

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Nick ODell
  • 15,465
  • 3
  • 32
  • 66
  • Can you explain what part of the error message you find confusing? I admit I'm used to Rust error messages, but it has nice arrows that point to things that seem pretty understandable to me. – Shepmaster Jan 28 '18 at 03:43
  • 2
    TL;DR the duplicate: You create a `String` by calling `to_string`, then take a reference to it via `as_str`. Since nothing owns the `String`, the reference is invalidated. However, you are trying to use the reference longer than it is invalid. In C or C++, this would likely have been compiled and only pose memory unsafety at run time. Instead, return a `String` or a `Cow`, if needed. – Shepmaster Jan 28 '18 at 03:48
  • 1
    FWIW, I'd write `self.number.map(|n| n.to_string()).unwrap_or_else(String::new)`. – Shepmaster Jan 28 '18 at 03:51
  • @Shepmaster Tried that. Doesn't work. Same error. – Nick ODell Jan 28 '18 at 03:53
  • 1
    [Works fine](https://play.rust-lang.org/?gist=8e6cff01b127054519d22c32e7a9f99a&version=stable). – Shepmaster Jan 28 '18 at 03:54

0 Answers0