3 ms·
Thank you grumbel and yrro, I get it. I'm used to write things like [&userId]() and was ignorant of "implicit" capture. Is there a benefit to the explicit vers
by nick__m 3y ago
Thank you grumbel and yrro, I get it. I'm used to write things like [&userId]() and was ignorant of "implicit" capture.
Is there a benefit to the explicit version or is this purely a stylistic matter?
- binary132 3y agoImplicit capture may capture more than you intended to. Explicit will cause the compiler to alert you to other names you might not have realized you included. It also makes it harder for people modifying your code to mess it up. That said, I usually use implicit because if I'm writing a lambda it's in a highly local context where a) it's just a shortcut, b) I know exactly what I'm doing, and c) it's not really meant for usability. If you want to make the intent really explicit and rigid, it might even be better to use a structured capturing type with an operator(): `MyCapture{.x = x, .y = y}()` or whatever.
- surajrmal 3y agoImplicit captures may not be obvious and may be accidental, leading to lifetime issues. Without a borrow checker like rust, it's safer to name them explicitly most of the time.
- dureuill 3y agoI wish we had the option to specify explicit captures in rust closures too. When you need it you need it, and it is good for clarity. The current "add `move` to switch from by-reference to by-value" is too coarse grained