package main
import "fmt"
type Inter interface {
run()
}
type todo struct {
name string
Inter
}
func (t *todo) run() {
fmt.Println("run")
fmt.Println(t.name)
}
func main() {
var in Inter = &todo{
name: "name",
}
in.run()
}
go run test2.go
run
name
2、基本接口实现调用结构体
package main
import "fmt"
type Inter interface {
run(map[string]string)
}
type car string
func (c *car) run(m map[string]string) {
fmt.Println(m)
}
func handlers(m map[string]string, h Inter) {
if m != nil && len(m) > 1 {
h.run(m)
}
}
func main() {
persons := map[string]string{
"bm": "bm",
"bc": "bc",
"vev": "vev",
}
var c *car
handlers(persons, c)
}
3、改变方法名,隐藏实现细节
package main
import "fmt"
type Inter interface {
Run(map[string]string)
}
type handFunc func(map[string]string)
func (h handFunc) Run(m map[string]string) {
h(m)
}
//转换的函数
func EachFunc(m map[string]string, f func(map[string]string)) {
Each(m, handFunc(f))
}
//调用函数
func Each(m map[string]string, f Inter) {
if m != nil && len(m) > 0 {
f.Run(m)
}
}
func PrintInfo(m map[string]string) {
fmt.Println(m)
}
func main() {
person := make(map[string]string)
person["bm"] = "bm"
person["bc"] = "bc"
person["vev"] = "vev"
EachFunc(person, PrintInfo)
}