Lazy evaluation & caching (lifetime problems)


I have a struct "Number" with i32 value.
There might be a need to transform it into something else (here: into a String).
I tried to use lazyness and caching but I stuck about lifetime problems.

There are two versions of the function I needed (to_str1 and to_str2). None of them can't compile.

I already read the docs about "borrowing/lifetimes/ownership". I used to get and fix this kind of problems (in other simple programs). But these defeated me.

Any advise is welcome.

I fixed up a few things: Rust Playground

Let me know if you have questions. The issue you initially hit is because format! returns a new String, but you tried to as_ref it - since that String has no owner it's a temp that's destroyed as soon as that scope (ie {}) ends.

1 Like

Thanks vitalyd!

I am surprised the temporary value 'dies' so early, before String::from() call.

Braces (i.e. {...} aka block expression) is a scope, and that puts a bound on the lifetime of values that were created in there. If you don't return those values out of that block expression (or assign them to something that keeps them alive longer), they die. In this case, the String dies before the String::from can use the &str to make a new String value. At any rate, it's better to just return the fresh String from those blocks so they're moved into the Some.