Skip to content

Instantly share code, notes, and snippets.

@ericchiang
Last active August 29, 2015 14:03
Show Gist options
  • Save ericchiang/07668b73c5837d97aaf8 to your computer and use it in GitHub Desktop.
Save ericchiang/07668b73c5837d97aaf8 to your computer and use it in GitHub Desktop.
Golang pointers
// This is a Gist to try to help you understand go pointers.
// You can run it in an interactive environment over on the go
// playground at: http://play.golang.org/p/pYTsfo6uhz
package main
import (
"fmt"
)
type MyStruct struct {
myField int
}
// This is a function that takes a pointer to a struct
// i.e. it takes the memory address of a struct
func SetFieldByPointer(s *MyStruct, newFieldVal int) {
fmt.Println("[SET POINTER] Incoming value: ", s)
s.myField = newFieldVal
fmt.Println("[SET POINTER] After assignment: ", s)
}
// This is a function that takes the actual values of a struct
func SetFieldByValue(s MyStruct, newFieldVal int) {
fmt.Println("[SET VALUE] Incoming value: ", s)
s.myField = newFieldVal
fmt.Println("[SET VALUE] After assignment: ", s)
}
func main() {
// new() returns a pointer to a struct, which is just the memory
// address of that struct
s := new(MyStruct)
s.myField = 5
// What happens to the local object when we pass the struct value?
fmt.Println("[MAIN FUNC] Before setting by value: ", s)
// Putting a '*' before an address will return the actual value
// storred in memory
SetFieldByValue(*s, 10)
fmt.Println("[MAIN FUNC] After setting by value: ", s)
// What happens to the local object when we pass the struct pointer?
fmt.Println("[MAIN FUNC] Before setting by pointer: ", s)
SetFieldByPointer(s, 13)
fmt.Println("[MAIN FUNC] After setting by pointer: ", s)
}
// OUTPUT:
// [MAIN FUNC] Before setting by value: &{5}
// [SET VALUE] Incoming value: {5}
// [SET VALUE] After assignment: {10}
// [MAIN FUNC] After setting by value: &{5}
// [MAIN FUNC] Before setting by pointer: &{5}
// [SET POINTER] Incoming value: &{5}
// [SET POINTER] After assignment: &{13}
// [MAIN FUNC] After setting by pointer: &{13}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment