当我们通过把一个现有(非interface)的类型定义为一个新的类型时,新的类型不会继承现有类型的方法。

神马意思?来一段简短错误的代码:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
package main
import "sync"
type myMutex sync.Mutex
func main() {
    var mtx myMutex
    mtx.Lock() 
    mtx.Unlock()
}

输出:

# command-line-arguments
.\mtx.Lock undefined (type myMutex has no field or method Lock)
.\ mtx.Unlock undefined (type myMutex has no field or method Unlock)

初步看代码貌似没啥问题。实际报错“myMutex类型没有字段或方法锁”?怎么解决?
如果我们确实需要原有类型的方法,可以定义一个新的struct类型,用匿名方式把原有类型嵌入进来即可:

package main
import "sync"
type myLocker struct {
    sync.Mutex
}
func main() {
    var mtx myLocker
    mtx.Lock()
    mtx.Unlock()
}

换成interface类型的声明也会保留它们的方法集合:

package main
import "sync"
type myLocker sync.Locker
func main() {
    var mtx  myLocker = new(sync.Mutex)
    mtx .Lock()
    mtx .Unlock()
}

类型声明和方法大家注意下即可。

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄