Skip to content

Confusion about the behavior of Dart closures capturing variables in loops #56991

@YuyeQingshan

Description

@YuyeQingshan

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-languageDart language related items (some items might be better tracked at github.com/dart-lang/language).type-questionA question about expected behavior or functionality

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions