I have a struct that contains Cow:
struct Subject<'a> {
inner: Cow<'a, str>
}
If a method returns an Owned variant, is it okay to specify the 'static lifetime? Or, more specifically, will the instance not live to the end of time?
pub fn from_string(s: String) -> Result<Subject<'static>, SubjectError> {
Ok(Subject { inner: Cow::Owned(s) })
}
Full code here (Rust Playground).
Yes. An owned Cow doesn't depend on any other data, so it can be kept alive as long as the caller wants.
1 Like
Variance should also allow someone to take that Subject<'static> and use it as any Subject<'a> they want.
1 Like
Note that Box::leak returns a &mut 'a T, not a &mut 'static T, so it's possible it should be
pub fn from_string(s: String) -> Result<Subject<'a>, SubjectError>
(I don't really know what the implications are for it.)
1 Like
I don't know why Box::leak needs to do that -- according to the nomicon on Variance, "&'a mut T is covariant over 'a but invariant over T", so I'd expect it could have just returned &'static mut T. I suppose that signature does let you call Box::leak::<'a>(b) without otherwise casting or coercing the lifetime.
edit: Oh, because it also requires T: 'a to make a legal reference, so it's more flexible this way than requiring T: 'static. This isn't an issue for the Subject given here, but could be something to consider if it had other generic parameters.
3 Likes
Aha! Silly thing, somehow I haven't even tried this variant.