Pointers
Go has pointers, but Go pointers is less intimidating that those in C/C++.
Basics
Here’s a simple example:
1 | var a int = 2 |
Note in C, the pointer is declared as int*
, but in Go it’s *int
. Also unlike pointers in C, pointers in Go cannot be calculated.
Types of Parameters Passing
With pointers and functions, we need to clarify the types of parameters passed in functions.
There are two types:
- pass by value
- pass by reference
In C, we could do either. For Python, most of the time it’s reference passing.
Review in C
1 |
|
The outputs will be:
1 | After pass_by_val: 3 |
Pass by Value will copy a value to the function; Pass by Reference will link the function to the value’s address by a pointer.
This actually creates confusion and complexity for the language.
Go Pass by Value Only
In Go, there’s only one method: pass by value. However we can simulate
pass by reference by using pointers.
Here’s a common example, swap two numbers.
1 | func swap(a, b int) { |
Go supports only pass by value, hence the above won’t swap at all.
1 | Before Swap: a = 3, b = 4 |
Now let’s define a new swap that takes two pointer parameters:
1 | func swap_ref(a, b *int) { |
The swap will be successful now:
1 | Before Swap: a = 3, b = 4 |
Alternatively we could define the swap function without using pointers:
1 | func swap_val(a, b int) (int, int) { |
The outputs will be
1 | Before Swap: a = 3, b = 4 |