What does "trait bound `for ...`" mean?

With this playground, I'm getting the following error:

error[E0277]: the trait bound `for<'r, 's> {integer}: std::ops::FnMut<(&'r regex::Captures<'s>,)>` is not satisfied
 --> src/main.rs:8:18

I know what the problem is in this trivial example, but this piece of for syntax is unfamiliar, so I'm afraid I wouldn't be able to figure out what to do if a similar error cropped up in a more complex setting.

To be clear, I know what a trait bound is in general, I'm confused specifically about the for part here. I'm sure there is already an explanation somewhere on the Internet, but it's hard to google for syntax... Especially since there's already a much more well-known use of for in Rust :slight_smile: Thanks for any pointers!

This is known as Higher Rank(ed) Trait Bound (HRTB) - that would be the term to google for more details. This SO answer is a good explanation of it.

1 Like

Higher Ranked Trait Bounds are also mentioned in the nomicon.

How on earth are we supposed to express the lifetimes on F's trait bound? We need to provide some lifetime there, but the lifetime we care about can't be named until we enter the body of call! Also, that isn't some fixed lifetime; call works with any lifetime &self happens to have at that point.

This job requires The Magic of Higher-Rank Trait Bounds (HRTBs). The way we desugar this is as follows:

where for<'a> F: Fn(&'a (u8, u16)) -> &'a u8,

(Where Fn(a, b, c) -> d is itself just sugar for the unstable real Fn trait)

for<'a> can be read as "for all choices of 'a", and basically produces an infinite list of trait bounds that F must satisfy. Intense. There aren't many places outside of the Fn traits where we encounter HRTBs, and even for those we have a nice magic sugar for the common cases.

1 Like