Last active
August 21, 2018 22:59
-
-
Save EnchanterIO/503038a0a3a48728a1301358e48e207a to your computer and use it in GitHub Desktop.
golang_mastery_struct_vs_object_pointer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright 2018 Lukas Lukac <https://lukaslukac.io>; All rights reserved. | |
// Play: https://play.golang.org/p/E34Y0SfAyK9 | |
package main | |
import ( | |
"fmt" | |
) | |
type illusion struct { | |
magicianCount int | |
} | |
func (i *illusion) increaseMagicianCount() { | |
i.magicianCount++ | |
} | |
func main() { | |
myIllusion := &illusion{} | |
myIllusion.increaseMagicianCount() | |
fmt.Println(myIllusion.magicianCount) // Expected: 1, Actual: 1 | |
// ↟ equivalent to ↡ | |
myIllusion = &illusion{} | |
increaseMagicianCount(myIllusion) | |
fmt.Println(myIllusion.magicianCount) // Expected: 1, Actual: 1 | |
increaseMagicianCount(nil) // I am evil developer | |
fmt.Println(myIllusion.magicianCount) // Expected: 1, Actual: 1 | |
} | |
func increaseMagicianCount(i *illusion) { | |
// with a value receiver you don't have to add unnecessary IF conditions and worry about panic attacks because | |
// is possible to receive NIL on a pointer receiver | |
if i == nil { | |
return | |
} | |
i.magicianCount++ | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment