如何在AsRef上使用生命周期 [英] How to use the lifetime on AsRef

查看:87
本文介绍了如何在AsRef上使用生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解下面的代码如何使用生命周期.我知道明确的生存期对于帮助编译器了解何时可以保存/释放数据是必需的,但是在这种特殊情况下,url.serialize()会生成一个匿名字符串,我不确定如何解决此问题.

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

推荐答案

一种便宜的参考到参考的转换.

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").

您没有告诉我们RequestUri::AbsoluteUriurl.serialize是什么库的,所以我只能猜测它返回了String.呼叫serialize的人可以拥有该字符串的所有权,也可以将其丢弃.

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.

在您的示例中,您使用String并在其上调用as_ref,这将返回&str.但是,什么都没有拥有String .块结束后,该String将被删除,所有引用都将无效.

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.

这篇关于如何在AsRef上使用生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆