4 ms·
Uhm, what if I didn't want `&OtherType` to have the same lifetime? Would I then write: fn f<'a>(x: &'a SomeType) -> &'b OtherType ?
by thomasahle 12y ago
Uhm, what if I didn't want `&OtherType` to have the same lifetime? Would I then write:
fn f<'a>(x: &'a SomeType) -> &'b OtherType
?
- kimundi 12y agoYes, though this particular code would not compile because one of the lifetimes is not declared.
- kibwen 12y agoThat would be illegal, because it only makes sense to return a reference when that reference is somehow linked to the lifetime of an input parameter. (Or when it has a lifetime of `static`, which means the referent is stored in static memory and thus is alive for the whole program.)
- thristian 12y agoWhat if you're looking up the input in a temporary cache of some kind, and returning a reference to the cached value? The lifetime of the input and output would not be related in that scenario, but the output would not necessarily be 'static (maybe you build a cache, run some functions, tear it all down, then build a new cache with different values and do it all again).
- steveklabnik 12y agoThe lifetime would be matched to the lifetime of the cache, which has to be referred to somehow.
- thomasahle 12y agoAh cool, I still have a lot to learn about rust :)
- TD-Linux 12y agoYou wouldn't use a reference generally, if you're thinking of creating a new independent object you'd just return that. This is for cases when your return object is a reference into your argument, for example