From 3abf036ebffbff59a7859c94c55d6a980ecc9483 Mon Sep 17 00:00:00 2001 From: Devin Jeanpierre Date: Wed, 4 Aug 2021 09:43:15 -0700 Subject: [PATCH] Document lifetime elision for fn types, Fn*, impl Currently, the lifetime elision doc only documents function definitions, but lifetime elision is also allowed in the following other locations: * `fn` types, such as `fn(&T)` * `Fn`/`FnMut`/`FnOnce`, such as `Fn(&T)` * `impl` headers To demo this up, I made some type aliases for `fn`/`Fn` which you can pass `&T` as a parameter to (to follow the lifetime rules of the surrounding context), and compared what you get with that instead of using `fn`/`Fn` directly, where lifetime elision takes on the rules from `fn`/`Fn`/etc. I also demoed up an `impl` header that used lifetime elision twice, although the error message in that case is broken (filed https://github.com/rust-lang/rust/issues/87763) The demo was half for this change description, and half just to make sure I understand Rust -- in particular, I really had to reverse engineer it for `impl` because I wasn't sure, and it didn't seem to be documented anywhere (at least not here!) https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=f82b280de4b992f225bc32121f333e96 --- src/lifetime-elision.md | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/lifetime-elision.md b/src/lifetime-elision.md index c65a157..dfa45ec 100644 --- a/src/lifetime-elision.md +++ b/src/lifetime-elision.md @@ -14,15 +14,17 @@ T<'a> Lifetime positions can appear as either "input" or "output": -* For `fn` definitions, input refers to the types of the formal arguments - in the `fn` definition, while output refers to +* For `fn` definitions, `fn` types, and the traits `Fn`, `FnMut`, and `FnOnce`, + input refers to the types of the formal arguments, while output refers to result types. So `fn foo(s: &str) -> (&str, &str)` has elided one lifetime in - input position and two lifetimes in output position. - Note that the input positions of a `fn` method definition do not - include the lifetimes that occur in the method's `impl` header - (nor lifetimes that occur in the trait header, for a default method). - -* In the future, it should be possible to elide `impl` headers in the same manner. + input position and two lifetimes in output position. Note that the input + positions of a `fn` method definition do not include the lifetimes that occur + in the method's `impl` header (nor lifetimes that occur in the trait header, + for a default method). + +* For `impl` headers, all types are input. So `impl Trait<&T> for Struct<&T>` + has elided two lifetimes in input position, while `impl Struct<&T>` has elided + one. Elision rules are as follows: