1

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..

tuskiomi
  • 190
  • 1
  • 15
  • 1
    Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/245834/discussion-on-question-by-tuskiomi-how-to-give-a-reference-an-explicit-lifetime). – Ryan M Jun 23 '22 at 05:53

1 Answers1

2

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(())
}
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • I cannot put a string into a `Result` because it will throw an 'unknown size at compile-time' error – tuskiomi Jun 23 '22 at 02:04
  • 1
    That error would come from `Result<(), str>` since `str` is an unsized type. `Result<(), String>` will definitely work. – John Kugelman Jun 23 '22 at 02:06
  • @JohnKugelman seems you're right: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1cf18412c259c88013b845132b2f6ca8 – tuskiomi Jun 23 '22 at 02:08