Go Tutorial Part 11 - Pointers and Struct
Contents
- Go by default is pass by value
- So passing a struct creates a copy
- &variable: returns memory address of the variable
- *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 Types | Zero value |
---|---|
int | slices |
float | maps |
string | channels |
bool | points |
structs | functions |