Pointers in ActionScript
We’ll translate the Go code to ActionScript and provide a suitable explanation in Markdown format, maintaining the overall structure and intent.
Go by Example: Pointers
Go supports [pointers](https://en.wikipedia.org/wiki/Pointer_(computer_programming)), allowing you to pass references to values and records within your program.
We’ll show how pointers work in contrast to values with 2 functions: `zeroval` and `zeroptr`. `zeroval` has an `int` parameter, so arguments will be passed to it by value. `zeroval` will get a copy of `ival` distinct from the one in the calling function.
```actionscript
function zeroval(ival:int):void {
ival = 0;
}
function zeroptr(iptr:Object):void {
iptr.value = 0;
}
function main():void {
var i:int = 1;
trace("initial:", i);
zeroval(i);
trace("zeroval:", i);
var iPtr:Object = { value: i };
zeroptr(iPtr);
i = iPtr.value;
trace("zeroptr:", i);
trace("pointer:", iPtr);
}
main();
zeroptr
in contrast has an Object
parameter, meaning that it takes a reference to an object containing an int
field. The iptr.value
code in the function body then dereferences the pointer from its memory address to the current value at that address. Assigning a value to a dereferenced pointer changes the value at the referenced address.
The iPtr
syntax gives us an object that acts like a pointer to i
.
Pointers can be printed too.
In this example, zeroval
doesn’t change the i
in main
, but zeroptr
does because it has a reference to the memory address for that variable.
initial: 1
zeroval: 1
zeroptr: 0
pointer: [object Object]
Next example: Strings and Runes.