@@ -7,8 +7,10 @@ compiler can infer a sensible default choice.
7
7
8
8
In order to make common patterns more ergonomic, Rust allows lifetimes to be
9
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.
10
+ An elided lifetime can be specified either by omitting it, or by using ` '_ ` .
11
+ For lifetimes in paths, using ` '_ ` is preferred. The following rules are used
12
+ to infer lifetime parameters for elided lifetimes. It is an error to elide
13
+ lifetime parameters that cannot be inferred.
12
14
13
15
* Each elided lifetime in the parameters becomes a distinct lifetime parameter.
14
16
* If there is exactly one lifetime used in the parameters (elided or not), that
@@ -23,6 +25,7 @@ Examples:
23
25
24
26
``` rust,ignore
25
27
fn print(s: &str); // elided
28
+ fn print(s: &'_ str); // also elided
26
29
fn print<'a>(s: &'a str); // expanded
27
30
28
31
fn debug(lvl: usize, s: &str); // elided
@@ -41,6 +44,7 @@ fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded
41
44
fn args<T: ToCStr>(&mut self, args: &[T]) -> &mut Command; // elided
42
45
fn args<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded
43
46
47
+ fn new(buf: &mut [u8]) -> BufWriter<'_>; // elided - preferred
44
48
fn new(buf: &mut [u8]) -> BufWriter; // elided
45
49
fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a>; // expanded
46
50
@@ -55,8 +59,12 @@ type FunTrait = for<'a> Fn(&'a str) -> &'a str; // expanded
55
59
56
60
The assumed lifetime of references held by a [ trait object] is called its
57
61
_ 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.
62
+ [ RFC 1156] .
63
+
64
+ > These default object lifetime bounds are used instead of the lifetime
65
+ > parameter elision rules defined above when the lifetime bound is omitted
66
+ > entirely. If ` '_ ` is used as the lifetime bound then the bound follows the
67
+ > usual elision rules.
60
68
61
69
If the trait object is used as a type argument of a generic type then the
62
70
containing type is first used to try to infer a bound.
@@ -136,7 +144,7 @@ struct BitsNStrings<'a> {
136
144
}
137
145
138
146
// BITS_N_STRINGS: BitsNStrings<'static>
139
- const BITS_N_STRINGS : BitsNStrings = BitsNStrings {
147
+ const BITS_N_STRINGS : BitsNStrings <' _ > = BitsNStrings {
140
148
mybits : [1 , 2 ],
141
149
mystring : STRING ,
142
150
};
0 commit comments