Is there any way to convert Cow<'_, str> to &str

Hi, thanks for your patient.
I encountered an problem when converting Cow<'_, str> to &str.
code:

use std::borrow::Cow;

pub fn convert(s: Cow<'_, str>) -> &str {
    s.as_ref()
}

// lifetime un-elided version, same result.
// pub fn convert<'a>(s: Cow<'a, str>) -> &'a str {
//    s.as_ref()
// }

fn main() {
    let s = Cow::from("hello");
    let s2 = convert(s);
    dbg!(s2);
}

And the error is:

error[E0515]: cannot return value referencing function parameter `s`
 --> examples/convert_ref.rs:6:5
  |
6 |     s.as_ref()
  |     -^^^^^^^^^
  |     |
  |     returns a value referencing data owned by the current function
  |     `s` is borrowed here

Isn't s in lifetime 'a? Or converting Cow<'_, str> to &str is a wrong doing?

1 Like

This is because if the Cow contains an owned string, that owned string is destroyed when you exit the function.

1 Like
fn convert<'a>(s: &'a Cow<'_, str>) -> &'a str {
    s.as_ref()
}

That would be the function you'd want, but I have a hard time figuring a use case for it. Cow itself needs to outlive the function's scope, else what it holds (be it an owned type or a reference) will be dropped.

3 Likes

@alice
Thanks very much for clear my mind on why it failed!

@erelde
Thanks very much for giving me the correct version.

Thank you for all your rapid replies!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.