Quidest?

Interface Values in Go

ยท Lorenzo Drumond

Under the hood, interface values can be thought of as a tuple of a value and a concrete type: (value, type)

An interface value holds a value of a specific underlying concrete type.

Calling a method on an interface value executes the method of the same name on its underlying type.

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

A nil interface value holds neither value nor concrete type.

Calling a method on a nil interface is a run-time error because there is no type inside the interface tuple to indicate which concrete method to call.

References

Next -> interface-values-with-nil-underlying-values-in-go

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