當我們通過把一個現有(非interface)的型別定義為一個新的型別時,新的型別不會繼承現有型別的方法,
神馬意思?來一段簡短錯誤的代碼:
package mainimport "sync"type myMutex sync.Mutexfunc 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 mainimport "sync"type myLocker struct { sync.Mutex}func main() { var mtx myLocker mtx.Lock() mtx.Unlock()}
換成interface型別的宣告也會保留它們的方法集合:
package mainimport "sync"type myLocker sync.Lockerfunc main() { var mtx myLocker = new(sync.Mutex) mtx .Lock() mtx .Unlock()}
型別宣告和方法大家注意下即可,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/53010.html
標籤:Go
