-1
請參閱下面的代碼:Golang:符合接口要求的類型別名結構
我有一種奇怪的行爲,我無法在Golang中理解。如果我想創建一個結構的類型別名,並且該結構符合接口類型的要求,那麼類型別名將不符合該接口類型的要求。我不知道爲什麼會發生這種情況。有什麼想法嗎?
package main
import (
"fmt"
)
type MyInt struct {
value int
}
func (m MyInt) DoubleIt() int {
return m.value * 2
}
type MyInter interface {
DoubleIt() int
}
type MyIntContainer struct {
d MyInter
}
type MC MyIntContainer
type MI MyInt
func main() {
e1 := MyIntContainer{MyInt{12}} //This is OK
fmt.Printf("%d\n", e1.d.DoubleIt())
e2 := MC{MI{12}} //this fails with error - line 29
fmt.Printf("%d\n", e2.d.DoubleIt())
}
錯誤消息: 第29行:在字段的值不能使用MI文字(類型MI)類型MyInter: MI沒有實現MyInter(缺少DoubleIt法)