Skip to content

Instantly share code, notes, and snippets.

@ianfoo
Created September 28, 2018 23:03
Show Gist options
  • Save ianfoo/4d3caa3a83dd3ace2ecc3f6175abafcc to your computer and use it in GitHub Desktop.
Save ianfoo/4d3caa3a83dd3ace2ecc3f6175abafcc to your computer and use it in GitHub Desktop.
// 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