How to give a reference an explicit lifetime in rust?

Viewed 56

I'm trying to return a Result<(), &str> in rust, where the &str has embedded data about any errors which have occurred. For example, say I have the following code:

struct Foo {
    pub mynum :i32,
}

impl Foo {
    fn do_something(&self) -> Result<(), &str> {
        if self.mynum % 12 == 0 {
            return Err(&format!("error! mynum is {}", self.mynum))
        }
        Ok(())
    }
}

fn main() {
    let foo_instance = Foo{
        mynum: 36,
    };
    let result = foo_instance.do_something().unwrap();
    println!("{:?}",result)
}

If I run this in the rust playground, I get

error[E0515]: cannot return value referencing temporary value
 --> src/main.rs:9:20
  |
9 |             return Err(&format!("error! mynum is {}", self.mynum))
  |                    ^^^^^-----------------------------------------^
  |                    |    |
  |                    |    temporary value created here
  |                    returns a value referencing data owned by the current function

which isn't desired. How do I tell the Rust compiler that to create a &str with lifetime 'a where 'a is the lifetime of self? I don't want to use 'static if possible, and I don't want to load Foo with extra members..

1 Answers

You should not return a &str in this case because the underlying object the &str is referencing gets dropped when the function terminates. Essentially, you are attempting to return a reference to a temporary value which gets deleted. See this article on differences between String and &str.

String is probably what you want instead. This compiles:

fn do_something(&self) -> Result<(), String> {
    if self.mynum % 12 == 0 {
        return Err(format!("error! mynum is {}", self.mynum));
    }
    Ok(())
}
Related