Contents

Go Tutorial Part 11 - Pointers and Struct

  1. Go by default is pass by value
  2. So passing a struct creates a copy
  3. &variable: returns memory address of the variable
  4. *pointer: give me value that exists at that memory address
package main

import "fmt"

type contactInfo struct {
	email   string
	zipCode int
}

type person struct {
	firstName string
	lastName  string
	contactInfo
}

func main() {
	jim := person{
		firstName: "Jim",
		lastName:  "Party",
		contactInfo: contactInfo{
			email:   "jim@gmail.com",
			zipCode: 9400,
		},
	}
	jimPointer := &jim
	jimPointer.updateName("jimmy")
	jim.print()
}

func (p person) print() {
	fmt.Printf("%+v", p)
}

func (pointerToPerson *person) updateName(newFirstName string) {
	(*pointerToPerson).firstName = newFirstName
}

Shortcut

	jimPointer := &jim
  jimPointer.updateName("jimmy")

func (pointerToPerson *person) updateName(newFirstName string) {
	(*pointerToPerson).firstName = newFirstName
}

can be written as

jim..updateName("jimmy")
func (pointerToPerson *person) updateName(newFirstName string) {
	(*pointerToPerson).firstName = newFirstName
}

because the receiver type instructs go to pass by reference

Value and Reference Types

Values TypesZero value
intslices
floatmaps
stringchannels
boolpoints
structsfunctions