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

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM