Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the lifetime on AsRef

Tags:

rust

lifetime

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() 
        }
    }
}
like image 395
user1243892 Avatar asked Nov 19 '25 14:11

user1243892


1 Answers

The docs for AsRef state:

A cheap, reference-to-reference conversion.

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 or url.serialize come from, so I can only guess that it returns a String. Whoever calls serialize can take ownership of the string, or can let it be dropped.

In your example, you take the String and call as_ref on that, which returns an &str. However, nothing owns the String. As soon as the block ends, that String 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.

like image 75
Shepmaster Avatar answered Nov 22 '25 02:11

Shepmaster