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?
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.