Quidest?

Interface values with nil underlying values in Go

ยท Lorenzo Drumond

If the concrete value inside the interface itself is nil, the method will be called with a nil receiver.

In some languages this would trigger a null pointer exception, but in Go it is common to write methods that gracefully handle being called with a nil receiver (as with the method M in this example.)

Note that an interface value that holds a nil concrete value is itself non-nil.

E.g.:

 1package main
 2
 3import "fmt"
 4
 5type I interface {
 6	M()
 7}
 8
 9type T struct {
10	S string
11}
12
13func (t *T) M() {
14	if t == nil {
15		fmt.Println("<nil>")
16		return
17	}
18	fmt.Println(t.S)
19}
20
21func main() {
22	var i I
23
24	var t *T
25	i = t
26	describe(i)
27	i.M()
28
29	i = &T{"hello"}
30	describe(i)
31	i.M()
32}
33
34func describe(i I) {
35	fmt.Printf("(%v, %T)\n", i, i)
36}
37
38// Output
39// (<nil>, *main.T)
40// <nil>
41// (&{hello}, *main.T)
42// hello

References

Next -> the-empty-interface-in-go

#nil #pointer #heap #interface #pass_by #golang #value #panic #stack #values #reference #methods #for_the_love_of_go #programming