Go使用变量类型声明和方法的注意事项

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

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

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()
}

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

posted @ 2019-12-18 17:06  周伯通之草堂  阅读(1404)  评论(0编辑  收藏  举报