'b: 'a means 'b lives at least as long as 'a
Conversation
It's like in math/logic where `x` means "any, but a fixed x" where `forall` means "any possible lifetime you could come up with".
1
1
Because you instruct the lifetime checker that it must prove all possible configurations safe. It's used especially for closures where the caller is not yet known.
1
2
If you use this feature wrong the right way, you will actually get error messages that give counter examples through inductive proof. "Assume a lifetime '0 that is allowed, there's a lifetime '1..."
1
2
It may be more accessible this way: If you have a function `fn x<'a>(&'a Something)` and you call it, the compiler has a concrete lifetime (the one of Something) to check. So it fills in the lifetime parameter through the actual time that Something lives.
1
But in the case of closures and some other things (which may be defined, but called _later_ in a function-like manner), we don't know the lifetime in the scope of the caller yet. So `for<'a>` means "independent of the situation at the call site, this must _always be safe_".
1
1
1
for<'a> is like a lambda for lifetimes; one will be provided later, and the type must work for any lifetime provided
3
1
Hmm just gotta be careful here, forall is not a lambda - it’s the type of a lambda! It gets a bit weird in Rust as they are only used within trait constraints, and you never see the corresponding lifetime functions, nor can you construct them yourself.
In hypothetical Rust:
let id : for<T> fn(x: T) -> T = <T>|x: T| -> T { x };
assert!(id::<i32>(3), 3);
assert!(id::<&str>("hi"), "hi");
1
(was meant to be `assert_eq!`)
See how `for` lets you write a `fn` type that depends on the type parameter `T` that is applied. Note that this is actually very similar to the `fn` type, just at the type level, and implicit.
2
Show replies




