Go接口实现是不依赖Go接口的定义--duck type 类似就可以
package _interface
import "testing"
type code string
type Programmer interface {
WirteHelloWolrd() code
}
type GoProgrammer struct {
}
func (g *GoProgrammer) WirteHelloWolrd() code{
return "fmt.Println(\"Hello wolrd\")"
}
func TestClient(t *testing.T){
var p Programmer
p = new(GoProgrammer)
t.Log(p.WirteHelloWolrd())
}
类型简化
package customer_type
import (
"fmt"
"testing"
"time"
)
type Innop = func(op int) int
func timeSpend(inner Innop) Innop{
return func(op int) int{
start := time.Now()
end := inner(op)
fmt.Println("time spent:",time.Since(start).Seconds())
return end
}
}
func slowFunc(op int) int {
time.Sleep(time.Second * 10)
return op
}
func TestFunc(t *testing.T){
tssf := timeSpend(slowFunc)
tssf(10)
}
本文探讨了Go语言中接口的实现方式,强调了接口实现并不依赖于接口定义,类似于鸭子类型的概念。通过代码示例展示了如何在不显式声明接口的情况下,通过类型的行为来满足接口要求。同时,还展示了如何使用函数类型来创建装饰器,以增加函数执行时的额外功能,例如计算执行时间。

被折叠的 条评论
为什么被折叠?



