How to use the lifetime on AsRef

独自空忆成欢 提交于 2019-12-11 05:43:35

问题


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.



来源:https://stackoverflow.com/questions/32062866/how-to-use-the-lifetime-on-asref

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!