I'm having a hard time understanding how to use lifetimes with the code below. I understand that explicit lifetimes are necessary to aid the compiler in understanding when it can hold/release data but in this particular case, url.serialize()
generates an anonymous string and I'm not really sure how to resolve this issue.
impl AsRef<str> for RequestUri {
#[inline]
fn as_ref(&self) -> &str {
match self {
&RequestUri::AbsoluteUri(ref url) => url.serialize().as_ref()
}
}
}
The docs for
AsRef
state:However, your code is not a reference-to-reference conversion, and it's not "cheap" (for certain interpretations of "cheap").
You don't tell us what library
RequestUri::AbsoluteUri
orurl.serialize
come from, so I can only guess that it returns aString
. Whoever callsserialize
can take ownership of the string, or can let it be dropped.In your example, you take the
String
and callas_ref
on that, which returns an&str
. However, nothing owns theString
. As soon as the block ends, thatString
will be dropped and any references will be invalid.There is no solution to the problem you have presented us using the information you've given.