简体   繁体   English

终身省略

[英]Lifetime elision

I have struct我有结构

struct Cursor<'a> {
    chars: Chars<'a>,
}

what's the difference between有什么区别

impl Cursor<'_> {
    fn new(input: &str) -> Cursor { ... }
}

and

impl<'a> Cursor<'a> {
    fn new(input: &'a str) -> Cursor<'a> { ... }
}

? ?

The difference is that the first version is desugared as:不同之处在于第一个版本被取消为:

impl<'a> Cursor<'a> {
    fn new<'b>(input: &'b str) -> Cursor<'b> { ... }
}

That is, there are two distinct lifetimes.也就是说,有两个不同的生命周期。

However, I'm having hard time imagining any actual difference.但是,我很难想象任何实际的差异。 The compiler will just infer to 'a to be some lifetime, and you'll work only with 'b , just like you work with 'a in the second version.编译器只会推断'a是某个生命周期,并且您只能使用'b ,就像您在第二个版本中使用'a一样。

It's to do with lifetime elision.这与终身省略有关。 To quote The Edition Guide :引用版本指南

Rust 2018 allows you to explicitly mark where a lifetime is elided, for types where this elision might otherwise be unclear. Rust 2018 允许您显式标记生命周期被省略的位置,对于这种省略可能不清楚的类型。 To do this, you can use the special lifetime '_ much like you can explicitly mark that a type is inferred with the syntax let x: _ =..;为此,您可以使用特殊的生命周期'_ ,就像您可以显式标记使用语法let x: _ =..;推断出的类型一样。 . .

Let's say, for whatever reason, that we have a simple wrapper around &'a str :假设无论出于何种原因,我们有一个简单的&'a str包装器:

 struct StrWrap<'a>(&'a str);

In Rust 2015, you might have written:在 Rust 2015 中,您可能写过:

 use std::fmt; fn make_wrapper(string: &str) -> StrWrap { StrWrap(string) } impl<'a> fmt::Debug for StrWrap<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.write_str(self.0) } }

In Rust 2018, you can instead write:在 Rust 2018 中,您可以改为:

 fn make_wrapper(string: &str) -> StrWrap<'_> { StrWrap(string) } impl fmt::Debug for StrWrap<'_> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.write_str(self.0) } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM