publish pointers

This commit is contained in:
Mark McGranaghan 2012-10-24 08:59:48 -04:00
parent ac5ced3fab
commit 1e78bcb2a7
3 changed files with 39 additions and 7 deletions

View File

@ -14,7 +14,7 @@ Multiple Return Values
Variadic Functions Variadic Functions
Closures Closures
Recursion Recursion
# Pointers Pointers
# New # New
# Structs # Structs
# Methods # Methods

View File

@ -1,14 +1,39 @@
// Go supports <em><a href="http://en.wikipedia.org/wiki/Pointer_(computer_programming)">pointers</a></em>,
// allowing you to pass references to values and records
// within your program.
package main package main
import "fmt" import "fmt"
func zero(xPtr *int) { // We'll show how pointers work in contrast to values with
*xPtr = 0 // 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.
func zeroval(ival int) {
ival = 0
}
// `zeroptr` in contrast has an `*int` parameter, meaning
// that it takes an `int` pointer. The `*iptr` 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.
func zeroptr(iptr *int) {
*iptr = 0
} }
func main() { func main() {
x := 5 i := 1
fmt.Println(x) fmt.Println("initial:", i)
zero(&x)
fmt.Println(x) zeroval(i)
fmt.Println("zeroval:", i)
// The `&i` syntax gives the memory address of `i`,
// i.e. a pointer to `i`.
zeroptr(&i)
fmt.Println("zeroptr:", i)
} }

View File

@ -0,0 +1,7 @@
# `zeroval` doesn't change the `i` in `main`, but
# `zeroptr` does because it has a reference to
# the memory address for that variable.
$ go run pointers.go
initial: 1
zeroval: 1
zeroptr: 0