go-learning/tour_of_go/l5/interfaces-continued.go

52 lines
535 B
Go
Raw Normal View History

2025-08-31 16:38:50 +00:00
package main
import (
"fmt"
"math"
)
type I interface {
M()
}
type T struct {
S string
}
func (t *T) M() {
if t == nil {
fmt.Println("<nil>")
return
}
fmt.Println(t.S)
}
type F float64
func (f F) M() {
fmt.Println(f)
}
func describe(i I) {
fmt.Printf("(%v, %T)\n", i, i)
}
func main() {
var i I
// These lines will cause a run-time error due to nil pointer dereferencing
// describe(i)
// i.M()
var t *T
i = t
describe(i)
i.M()
i = &T{"hello"}
describe(i)
i.M()
i = F(math.Pi)
describe(i)
i.M()
}