-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Description
Recently, I came across some code in tests/language/loop/for_variable_capture_test.dart that has piqued my interest regarding how Dart handles variable capture in closures within loops. I'm looking to gain a deeper understanding of this behavior, as it seems to have some nuances that I'm not fully grasping.
Here's the code snippet:
initializer() {
var closure;
for (var i = 0, fn = () => i; i < 3; i++) {
i += 1;
closure = fn;
}
Expect.equals(1, closure());
}The Expect statement in the code passes, indicating that the value returned by the closure() is 1.
I also rewrite the equivalent code in Swift and JavaScript, and in those languages, calling the closure returns a value of 4, which aligns more with my expectations. While Dart does not seem to handle this in the same way, and I'm curious about the rules governing this behavior.
Could someone please explain the rules, and Thank you in advance for any insights you can offer!
Dart info
- Dart 3.1.5 (stable) (Tue Oct 24 04:57:17 2023 +0000) on "macos_arm64"
- on macos / Version 14.5 (Build 23F79)
- locale is zh-Hans-CN