Created
September 28, 2018 23:03
-
-
Save ianfoo/4d3caa3a83dd3ace2ecc3f6175abafcc to your computer and use it in GitHub Desktop.
On Go Playground: https://play.golang.org/p/UMBzhz3JErE
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
// This illustrates how you can call a method on a nil pointer type | |
// if it doesn't dereference the nil value. | |
package main | |
import "fmt" | |
type T int | |
func (t *T) hello() string { | |
return "Hi there!" | |
} | |
func (t *T) ensure() *T { | |
if t == nil { | |
t = new(T) | |
} | |
return t | |
} | |
func (t *T) set(x int) { | |
*t = T(x) | |
} | |
func (t T) String() string { | |
return fmt.Sprintf("The value is %d\n", t) | |
} | |
func main() { | |
var t *T | |
fmt.Println(t, t.hello()) | |
t = t.ensure() | |
t.set(4) | |
fmt.Println(t) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment