@@ -5,10 +5,14 @@ compiler can infer a sensible default choice.
55
66## Lifetime elision in functions
77
8- In order to make common patterns more ergonomic, Rust allows lifetimes to be
9- * elided* in [ function item] , [ function pointer] and [ closure trait] signatures.
10- The following rules are used to infer lifetime parameters for elided lifetimes.
11- It is an error to elide lifetime parameters that cannot be inferred.
8+ In order to make common patterns more ergonomic, Rust allows lifetime argument
9+ to be * elided* in [ function item] , [ function pointer] and [ closure trait]
10+ signatures. The following rules are used to infer lifetime parameters for
11+ elided lifetimes. It is an error to elide lifetime parameters that cannot be
12+ inferred. The placeholder lifetime, ` '_ ` , can also be used to have a lifetime
13+ inferred in the same way. For lifetimes in paths, using ` '_ ` is preferred.
14+ Trait object lifetimes follow different rules discussed
15+ [ below] ( #default-trait-object-lifetimes ) .
1216
1317* Each elided lifetime in the parameters becomes a distinct lifetime parameter.
1418* If there is exactly one lifetime used in the parameters (elided or not), that
@@ -23,6 +27,7 @@ Examples:
2327
2428``` rust,ignore
2529fn print(s: &str); // elided
30+ fn print(s: &'_ str); // also elided
2631fn print<'a>(s: &'a str); // expanded
2732
2833fn debug(lvl: usize, s: &str); // elided
@@ -41,6 +46,7 @@ fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded
4146fn args<T: ToCStr>(&mut self, args: &[T]) -> &mut Command; // elided
4247fn args<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded
4348
49+ fn new(buf: &mut [u8]) -> BufWriter<'_>; // elided - preferred
4450fn new(buf: &mut [u8]) -> BufWriter; // elided
4551fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a>; // expanded
4652
@@ -55,8 +61,12 @@ type FunTrait = for<'a> Fn(&'a str) -> &'a str; // expanded
5561
5662The assumed lifetime of references held by a [ trait object] is called its
5763_ default object lifetime bound_ . These were defined in [ RFC 599] and amended in
58- [ RFC 1156] . Default object lifetime bounds are used instead of the lifetime
59- parameter elision rules defined above.
64+ [ RFC 1156] .
65+
66+ > These default object lifetime bounds are used instead of the lifetime
67+ > parameter elision rules defined above when the lifetime bound is omitted
68+ > entirely. If ` '_ ` is used as the lifetime bound then the bound follows the
69+ > usual elision rules.
6070
6171If the trait object is used as a type argument of a generic type then the
6272containing type is first used to try to infer a bound.
@@ -136,7 +146,7 @@ struct BitsNStrings<'a> {
136146}
137147
138148// BITS_N_STRINGS: BitsNStrings<'static>
139- const BITS_N_STRINGS : BitsNStrings = BitsNStrings {
149+ const BITS_N_STRINGS : BitsNStrings <' _ > = BitsNStrings {
140150 mybits : [1 , 2 ],
141151 mystring : STRING ,
142152};
0 commit comments