Dart中原始类型为何表现类似引用类型?闭包代码示例解析
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:
int i = 10;: We create an immutableintobject with value10, and the variableireferences this object.- Define
someFunc: The closure references the variablei. Instead of copying the current value ofi(10) into the closure, it captures a reference to the variableiitself. i = 20;: We create a new immutableintobject with value20, and update the variableito reference this new object. The original10object becomes unreachable (and will be garbage collected later).someFunc();: When we run the closure,int ni = i;looks up the current value of the captured variablei—which now points to the20object. Sonigets assigned20, 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
intin 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

