本文介绍了用简单的术语来说,终生淘汰是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 Rust文档:

我不明白这是什么意思.什么是物品签名? 推断寿命参数"是什么意思?一些例子或类比会有所帮助.

I don't understand what this means. What are item signatures? What does "infer lifetime parameters" mean? Some examples or analogies would be helpful.

推荐答案

项目签名是给出函数名称和类型的位,即您需要调用的所有内容(无需知道其实现方式);例如:

An item signature is the bit which gives the name and types of your function, i.e. everything you need to call it (without needing to know how it's implemented); for example:

fn foo(x: u32) -> u32;

这里有一个引用&str的引用:

Here's another which takes a &str reference:

fn bar<'a>(s: &'a str) -> &'a str;

在Rust中,所有引用都有附加的生存期;这是这种类型的一部分.上面的bar函数说的不只是该函数引用一个字符串并返回另一个字符串".它说:此函数接受一个字符串引用,并返回另一个,它在给定的时间内一直有效.这是Rust所有权系统的重要组成部分.

In Rust, all references have an attached lifetime; this is part of the type. The above bar function says more than just "this function takes a reference to a string and returns another one". It says "this function takes a string reference, and returns another which is valid for as long as the one it's given. This is an important part of Rust's ownership system.

但是,每次指定这些生存期都是令人烦恼和痛苦的事情,因此Rust具有生存期淘汰"(即未明确写出")的麻烦.这意味着在一些非常常见的情况下,您可以省略生命周期注释,Rust会为您隐式添加它们.纯粹是为了方便程序员,这样他们就不必在明显"的情况下写那么多的生存期.

However, it's annoying and a pain to specify these lifetimes every time, so Rust has "lifetime elision" (i.e. "not explicitly writing them out"). All that means is that for a few very common cases, you can leave the lifetime annotations out and Rust will implicitly add them for you. This is purely a convenience for programmers so that they don't have to write so many lifetimes in "obvious" cases.

这本书中列出了这些规则,但对于完整性是:

The rules are listed in the book, but for completeness they are:

  1. 未另外指定的功能参数中的每个生存期都不同.例如:
fn f(x: &T, y: &U)

表示:

fn f<'a, 'b>(x: &'a T, y: &'b U)

即这些生命周期之间没有自动链接.

i.e. there's no automatic link between those lifetimes.

  1. 如果只有一个输入寿命,那么它将用于每个输出寿命.例如:
struct U<'a> {}  // struct with a lifetime parameter

fn f(x: &T) -> &U

成为:

fn f<'a>(x: &'a T) -> &'a U<'a>
  1. 否则,如果有多个输入生存期,但其中一个是&self&mut self(即这是一种方法),则所有被忽略的输出生存期都将与self相同.这涵盖了方法返回对其字段之一的引用的常见情况.例如:
  1. Otherwise, if there are multiple input lifetimes but one of them is &self or &mut self (i.e. it's a method), then all the elided output lifetimes get the same as self. This covers the common case that a method returns a reference to one of its fields. For example:
impl S {
    fn get_my_item(&self, key: &str) -> &str {}
}

成为:

fn get_my_item<'a,'b>(&'a self, key: &'b str) -> &'a str  // use the self lifetime

该文档还有更多示例.

这篇关于用简单的术语来说,终生淘汰是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 03:24