Lazy evaluation & caching (lifetime problems)


#1

Hi,

https://play.rust-lang.org/?gist=a4f4b53e116fd27b1eec6049febc9ecc&version=stable

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.


#2

I fixed up a few things: https://play.rust-lang.org/?gist=f3aaee67be4fc3ad8bb185de84ed0f7e&version=stable

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.


#3

Thanks vitalyd!

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


#4

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.