How to use the lifetime on AsRef

2019-08-15 00:25发布

问题:

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() 
        }
    }
}

回答1:

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.



标签: rust lifetime