From 1e78bcb2a7c0b287f26b4cb2cedceb45ff37f651 Mon Sep 17 00:00:00 2001 From: Mark McGranaghan Date: Wed, 24 Oct 2012 08:59:48 -0400 Subject: [PATCH] publish pointers --- examples.txt | 2 +- examples/pointers/pointers.go | 37 +++++++++++++++++++++++++++++------ examples/pointers/pointers.sh | 7 +++++++ 3 files changed, 39 insertions(+), 7 deletions(-) create mode 100644 examples/pointers/pointers.sh diff --git a/examples.txt b/examples.txt index 3fffb46..3d76288 100644 --- a/examples.txt +++ b/examples.txt @@ -14,7 +14,7 @@ Multiple Return Values Variadic Functions Closures Recursion -# Pointers +Pointers # New # Structs # Methods diff --git a/examples/pointers/pointers.go b/examples/pointers/pointers.go index 302ec78..2d5ecf6 100644 --- a/examples/pointers/pointers.go +++ b/examples/pointers/pointers.go @@ -1,14 +1,39 @@ +// Go supports pointers, +// allowing you to pass references to values and records +// within your program. + package main import "fmt" -func zero(xPtr *int) { - *xPtr = 0 +// 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. +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() { - x := 5 - fmt.Println(x) - zero(&x) - fmt.Println(x) + i := 1 + fmt.Println("initial:", i) + + 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) } diff --git a/examples/pointers/pointers.sh b/examples/pointers/pointers.sh new file mode 100644 index 0000000..7dcab24 --- /dev/null +++ b/examples/pointers/pointers.sh @@ -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