// main project main.go
package main
import (
"fmt"
)
type Stringer interface {
String() string
}
type intStr struct {
i int
}
func (s *intStr) String() string {
return fmt.Sprintf("%d", s.i)
}
func Print(s Stringer) {
fmt.Println(s.String())
}
func DynamicPrint(any interface{}) {
if s, ok := any.(Stringer); ok {
Print(s)
}
}
func main() {
// 1
var num intStr
num.i = 12345
Print(&num)
DynamicPrint(&num)
//2
num2 := &intStr{i: 10086}
Print(num2)
DynamicPrint(num2)
//3
var num3 Stringer = new(intStr)
fmt.Println(num3.String())
Print(num3)
DynamicPrint(num3)
//4
var num4 *intStr = new(intStr)
num4.i = 345
Print(num4)
DynamicPrint(num4)
fmt.Println(num4.String())
}
输出:
12345
12345
10086
10086
0
0
0
345
345
345
有疑问加站长微信联系(非本文作者)