[Login]

go/cheat sheet

Passing by value and passing by reference

Try at: https://play.golang.org/p/lNpnS9j1ma

// Allowed:
p := Person{"Hillary", 28} 	// stores the value
p := &Person{"Hillary", 28} 	// stores the pointer address (reference)
PrintPerson(p) 			// passes either the value or pointer address (reference)
PrintPerson(*p) 		// passes the value
PrintPerson(&p) 		// passes the pointer address (reference)
func PrintPerson(p Person)	// ONLY receives the value
func PrintPerson(p *Person)	// ONLY receives the pointer address (reference)

// Not Allowed:
p := *Person{"Hillary", 28} 	// illegal
func PrintPerson(p &Person)	// illegal

Example: https://play.golang.org/p/GfXPs8vCT8l

package main
import "fmt"

func ps(s *string) {
	fmt.Println(s)  // prints "0x40e128"
	fmt.Println(*s) // prints "boo"
	*s = "hoo"
}
func main() {
	s := "boo"
	ps(&s)
	fmt.Println(s) // prints "hoo"
}