当我们通过把一个现有(非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()
}

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

相关文章:

  • 2021-11-06
  • 2021-04-20
  • 2022-12-23
  • 2021-12-16
  • 2021-06-22
  • 2019-11-22
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-05-16
  • 2022-12-23
  • 2021-11-12
  • 2021-11-05
  • 2022-03-04
相关资源
相似解决方案