#Making an own-able struct of Cows

11 messages · Page 1 of 1 (latest)

chrome tapir
#

Behold the following: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1ca7f62bcf7540e35171195d5751833a

It's a struct full of cows for str.
I would like to be able to use block_tag.to_owned() to get an owned version of the BlockTag, which is just a BlockTag<'static>.
You can see in this playground that it gives me a lifetime error though, which confuses me since the owned type shouldn't be dependent on the lifetime of the borrowed type, right?

rare oyster
#

the owned type shouldn't be dependent on the lifetime of the borrowed type, right?
It is, in the case of Cow.

The reason for that is that a Cow is not very useful past the lifetime where it would be valid if it was borrowed

#

To elaborate, if you have a Cow<'a, str> and you keep it around for longer than 'a (you can't actually do this, pretend you could), then you can't access it anymore unless you're certain it's owned: if it was borrowed, you'd be accessing a dangling reference

#

But if you're certain it's owned, why do you even have a Cow

#

Just have a String, or in general the owned type

#

Now, as you noticed there is a valid reason to have a Cow where you're certain it's owned, but .to_owned() on Cow doesn't actually "decouple" the lifetime.

#

(that's because Cow doesn't implement ToOwned, it's just Clone. You're calling the default implementation of ToOwned for Clone types)

#

To decouple it by hand, you can use Cow::Owned(cow.into_owned()), which will convert to owned (or extract the existing owned contents), then put them in a new cow, which can have a different lifetime

chrome tapir
#

Ohhh now that makes sense.

#

Thanks. I had a feeling I was missing something simple.

#

That explains why the owned type can't just be a 'static version of the original type.