3 ms·
Wow, Python and Go have it too? It was the biggest wart of pre-ES6 JavaScript, I never imagined other languages had it too (and it's honestly very disappointin
by littlestymaar 4y ago
Wow, Python and Go have it too? It was the biggest wart of pre-ES6 JavaScript, I never imagined other languages had it too (and it's honestly very disappointing for Go, since it's much more recent and we had plenty of hindsight when it was created…)
Edit: looks like Rust does it right: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=aec1261e40a7880e6882f6502a34abde https://play.rust-lang.org/?version=stable&mode=debug&editio...
- kevincox 4y agoNot quite how you tested it. The `move` is actually copying the variable: fn main() { let mut functions = vec![]; let mut i = 0; functions.push(Box::new(move || println!("Hello {i}")) as Box<dyn Fn()>); i = 1; functions.push(Box::new(move || println!("Hello {i}"))); i = 2; functions.push(Box::new(move || println!("Hello {i}"))); for func in functions { func(); } } But the most equivalent code would be the following which doesn't compile: fn main() { let mut functions = vec![]; for i in 0..10 { functions.push(Box::new(|| println!("Hello {i}"))) } for func in functions { func(); } }
- littlestymaar 4y agoThat's the point: the misleading code doesn't compile because the `i` variable scope in limited to the current execution of the loop (and that's why you can't borrow it for `functions`'s lifetime), which is exactly how ES6 fixed this in JavaScript.