我斷言指向結構的指標的型別在 golang 中實作了一個介面,并且在下面的代碼示例中有一些我不理解的東西:
package main
import (
"fmt"
)
type MyStruct struct {
Name string
}
func (m *MyStruct) MyFunc() {
m.Name = "bar"
}
type MyInterface interface {
MyFunc()
}
func main() {
x := &MyStruct{
Name: "foo",
}
var y interface{}
y = x
_, ok := y.(MyInterface)
if !ok {
fmt.Println("Not MyInterface")
} else {
fmt.Println("It is MyInterface")
}
}
我期待這樣做,_, ok := y.(*MyInterface)因為y它是一個指向MyStruct. 為什么我不能斷言它是一個指標?
uj5u.com熱心網友回復:
型別斷言用于查找介面中包含的物件的型別。所以,y.(MyInterface)作業,因為包含在介面中的物件y是 a *MyStruct,并且它實作了MyInterface。但是,*MyInterface不是介面,它是指向介面的指標,所以您要斷言的是是否y是 a *MyInterface,而不是是否yimplements MyInterface。只有在以下情況下才會成功:
var x MyInterface
var y interface{}
y=&x
_, ok := y.(*MyInterface)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/453000.html
標籤:走
上一篇:何時使用未命名型別?
