不带任何参数的方法的显式生命周期的意义何在? [英] What is the point of an explicit lifetime for a method that doesn't take any arguments?

查看:94
本文介绍了不带任何参数的方法的显式生命周期的意义何在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Programming Rust 的第295页上,您可以找到以下内容:

On page 295 of Programming Rust you can find the following:

幸运的是,该标准库包括一揽子实施方案:

Fortunately, the standard library includes the blanket implementation:

impl<'a, T, U> AsRef<U> for &'a T
where
    T: AsRef<U>,
    T: ?Sized,
    U: ?Sized,
{
    fn as_ref(&self) -> &U {
        (*self).as_ref()
    }
}

我对在那里使用&'a感到困惑.那是什么背景?它没有在as_ref的参数中使用,也没有与&U的输出绑定.在这种情况下使用时,我认为我并不完全了解生命周期.

I'm confused at the use of &'a there. What is the context of that? It's not being used in an argument of as_ref nor tied to the output of &U. I don't think I fully understand lifetimes when used in this context.

我进行了查找,因为我仍然不了解它,并且答案仍然没有点击(说得通).我发现 convert.rs .这似乎在任何地方都没有 any 生存期,但是它实现了AsRef特性.那么,为什么书中有此内容,而不是Rust中的实际代码呢?在哪里可以找到书中提到的全面实施"?

I looked this up because I still didn't understand it and the answers still weren't clicking (making sense). I found convert.rs. This doesn't seem to have any lifetimes anywhere, but it implements the AsRef trait. So why does the book have this, and not the actual code in Rust? Where can I find the "blanket implementation" mentioned in the book?

推荐答案

as_ref

最肯定的是.该函数使用速记符号,可以将其扩展:

It most certainly is. The function uses a shorthand notation, which can be expanded:

fn as_ref(&self) // becomes
fn as_ref(self: &Self) // becomes
fn as_ref(self: &&'a T)

也未绑定到&U

正确.

那为什么书里有这个,而不是Rust中的实际代码?

So why does the book have this, and not the actual code in Rust?

Rust每6周发布一次新的稳定版本.大概这本书没有,所以很可能他们使用的是Rust的旧版本.希望本书能告诉您他们开发的版本.

Rust releases new stable versions every 6 weeks. Presumably the book does not, so it is likely that they are using an older version of Rust. Hopefully the book tells you the version they developed with.

E_net4所述,在这种情况下,指定'a的要求已在Rust 1.31中删除,因为版本指南.

As E_net4 already stated, the requirement to specify the 'a in this case was removed in Rust 1.31, as documented in the edition guide.

您从书中提供的代码与在Rust 1.30中找到:

The code you provide from the book matches that found in Rust 1.30:

impl<'a, T: ?Sized, U: ?Sized> AsRef<U> for &'a T where T: AsRef<U>
{
    fn as_ref(&self) -> &U {
        <T as AsRef<U>>::as_ref(*self)
    }
}

您查看的源代码

impl<T: ?Sized, U: ?Sized> AsRef<U> for &T where T: AsRef<U>
{
    fn as_ref(&self) -> &U {
        <T as AsRef<U>>::as_ref(*self)
    }
}

这大约需要42周的开发时间,许多源代码都已更改.

This is about 42 weeks of development time, plenty for the source code to have changed.

这篇关于不带任何参数的方法的显式生命周期的意义何在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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