rust-lang / reference

The Rust Reference
https://doc.rust-lang.org/nightly/reference/
Apache License 2.0
1.16k stars 452 forks source link

Fix syntax in `'static lifetime elision` section of `lifetime-elision.md` #1463

Closed felix-andreas closed 3 months ago

felix-andreas commented 3 months ago

Hi, (warning: not a Rust expert) there was a small thing that confused me while reading:

In one of the examples in the 'static lifetime elision section of the lifetime-elision chapter, I got the following error messages when trying out the explicit (non-elided) form.

Example:

// Resolved as `fn<'a>(&'a str) -> &'a str`.
const RESOLVED_SINGLE: fn(&str) -> &str = |x| x;

// Resolved as `Fn<'a, 'b, 'c>(&'a Foo, &'b Bar, &'c Baz) -> usize`.
const RESOLVED_MULTIPLE: &dyn Fn(&Foo, &Bar, &Baz) -> usize = &somefunc;

First case (function pointer):

error: function pointer types may not have generic parameters
 --> interaction-core/src/bin/foo.rs:5:26
  |
5 | const RESOLVED_SINGLE: fn<'a>(&'a str) -> &'a str = |x| x;
  |                          ^^^^
  |
help: consider moving the lifetime parameter to a `for` parameter list
  |
5 - const RESOLVED_SINGLE: fn<'a>(&'a str) -> &'a str = |x| x;
5 + const RESOLVED_SINGLE: for<'a> fn(&'a str) -> &'a str = |x| x;

Second case (closure trait):

error: `Fn` traits cannot take lifetime parameters
 --> interaction-core/src/bin/foo.rs:6:33
  |
6 | const RESOLVED_MULTIPLE: &dyn Fn<'a, 'b, 'c>(&'a Foo, &'b Bar, &'c Baz) -> usize = &somefunc;
  |                                 ^^^^^^^^^^^^
  |
help: consider using a higher-ranked trait bound instead
  |
6 - const RESOLVED_MULTIPLE: &dyn Fn<'a, 'b, 'c>(&'a Foo, &'b Bar, &'c Baz) -> usize = &somefunc;
6 + const RESOLVED_MULTIPLE: &dyn for<'a, 'b, 'c> Fn(&'a Foo, &'b Bar, &'c Baz) -> usize = &somefunc;

From the error messages, I conclude, that fn<'a>(&'a str) -> &'a str and Fn<'a, 'b, 'c>(&'a Foo, &'b Bar, &'c Baz) -> usize are not valid syntax for function pointers or closure traits and higher-ranked trait bound must be used instead.

I fixed the comments in the example according to the error message and verified that it compiles.

matthewjasper commented 3 months ago

Thanks