You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart中原始类型为何表现类似引用类型?闭包代码示例解析

Why does a primitive type like int behave like a reference type in this Dart closure example?

Great question! Let's clear up the confusion here—this behavior has nothing to do with int being a reference type, and everything to do with how Dart closures capture variables. Let's break down your code step by step:

void main() { 
  int i = 10; 
  var someFunc = () { 
    int ni = i; 
    print(ni); 
  }; 
  i = 20; 
  someFunc(); // Outputs 20 
}

Key Background: Dart Variables & Closures

First, a quick refresher to set context:

  • In Dart, all variables are references to objects—even int (which is an immutable value type under the hood). But that's not why your code outputs 20.
  • Dart closures capture the variable itself (its binding), not the value the variable points to at the time the closure is defined. That's the critical detail driving this behavior.

Step-by-Step Execution

Let's walk through exactly what happens line by line:

  1. int i = 10;: We create an immutable int object with value 10, and the variable i references this object.
  2. Define someFunc: The closure references the variable i. Instead of copying the current value of i (10) into the closure, it captures a reference to the variable i itself.
  3. i = 20;: We create a new immutable int object with value 20, and update the variable i to reference this new object. The original 10 object becomes unreachable (and will be garbage collected later).
  4. someFunc();: When we run the closure, int ni = i; looks up the current value of the captured variable i—which now points to the 20 object. So ni gets assigned 20, and that's what gets printed.

How to Prove It's Not About int Being a Reference Type

To confirm this is a closure behavior, not an int type behavior, let's modify the code to capture a static value instead of the variable:

void main() { 
  int i = 10; 
  var capturedValue = i; // Capture the value at this fixed point
  var someFunc = () { 
    int ni = capturedValue; 
    print(ni); 
  }; 
  i = 20; 
  someFunc(); // Outputs 10 
}

Here, capturedValue holds the original 10 value (since we never reassign it), so the closure outputs 10—even though i was updated later. This clearly shows the difference between capturing a variable's binding vs. capturing a static value.

Summary

  • int in Dart is still an immutable value type, not a reference type.
  • The "reference-like" behavior you're seeing comes from Dart closures capturing variable bindings, not static values. When you reassign the variable after defining the closure, the closure will use the variable's latest value when it runs.

内容的提问来源于stack exchange,提问作者Sergey Shirnin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:35:14