Go has a pointer type which is similar to the one in C++.
- Use the asterisk in declarations, var p *string
- Also use it to de-reference, *p = "Hello"
- Use the ampersand to create a pointer to a variable,
s := "Greetings" ; p = &s
- Or allocate one with new, p = new(string)
- No need to free; pointers are garbage-collected
- Likewise, no need to remember if you created the pointer with
& or new.
- No special relationship between pointers and arrays.
- No pointer arithmetic.
/*
* Go has a pointer type much like C++, except data allocated with new does
* not need to be freed by the user.
*/
package main
import "fmt"
// Pointer parameter. Updates what p points to, but, of course
// the variable sent to q is not changed.
func stuff(p *int, q int) {
*p += q;
q = 99
}
// A function that allocates and returns a pointer
func maker(v int) *int {
ret := new(int)
*ret = v
return ret
}
func main() {
// C-ish pointer games.
var q *int
a := 10
q = &a
*q += 3
// Some function things
b := 15
stuff(&b, a)
c := maker(30)
fmt.Printf("%d %d %d\n", a, b, *c)
}