Pointers in Dart
Dart supports references to objects, which are similar to pointers in other languages. However, Dart doesn’t have explicit pointer types or pointer arithmetic. Instead, all objects in Dart are referred to by reference.
Here’s an example demonstrating how references work in Dart:
In this example, we demonstrate the difference between passing by value and passing by reference in Dart:
The
zeroval
function takes anint
parameter. In Dart, integers are immutable and passed by value, so changes toival
inside the function don’t affect the original variable.The
zeroref
function takes aList<int>
parameter. Lists in Dart are objects and are passed by reference. By modifying the first element of the list, we can simulate changing the value of the original variable.In the
main
function, we first callzeroval
, which doesn’t change the original value ofi
.Then we create a list
iref
containingi
, callzeroref
with this list, and updatei
with the modified value from the list. This simulates passing by reference and allows us to modify the original variable.Finally, we print the
hashCode
ofi
. In Dart, we can’t directly print memory addresses like in some other languages, buthashCode
provides a unique identifier for the object.
When you run this program, you’ll see output similar to:
This output shows that zeroval
doesn’t change the original value, while zeroref
does modify it. The hashCode
is printed to demonstrate how we might identify unique objects in Dart, although it’s not directly equivalent to a memory address.
Remember, Dart manages memory automatically and doesn’t expose direct memory manipulation like some lower-level languages do. This design choice helps prevent common programming errors while still allowing efficient memory usage.