duanrong6802
duanrong6802
2016-05-29 07:55
浏览 50
已采纳

Golang:满足接口要求的类型别名结构

See code below:

I have an odd behavior that I can't understand in Golang. If I want to create a type alias of a structure and that structure meets the requirements of a interface type, then the type alias won't meet the requirements of that interface type. I have no idea why this is happening. Any thoughts?

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
", e1.d.DoubleIt())
    e2 := MC{MI{12}} //this fails with error - line 29
    fmt.Printf("%d
", e2.d.DoubleIt())
}

The error message: Line 29: cannot use MI literal (type MI) as type MyInter in field value: MI does not implement MyInter (missing DoubleIt method)

图片转代码服务由CSDN问答提供 功能建议

请参见下面的代码:

我有一种奇怪的行为,我可以 不懂Golang。 如果我要创建结构的类型别名,并且该结构满足接口类型的要求,则类型别名将不满足该接口类型的要求。 我不知道为什么会这样。 有什么想法吗?

 包main 
 
import(
“ fmt” 
)
 
type MyInt struct {
 value int 
} 
 
func  (m MyInt)DoubleIt()int {
返回m.value * 2 
} 
 
type MyInter接口{
 DoubleIt()int 
} 
 
type MyIntContainer struct {
d MyInter 
} \  n 
type MC MyIntContainer 
type MI MyInt 
 
func main(){
 e1:= MyIntContainer {MyInt {12}} // //可以
 fmt.Printf(“%d 
”,e1.d  .DoubleIt())
 e2:= MC {MI {12}} //此操作因错误而失败-第29行
 fmt.Printf(“%d 
”,e2.d.DoubleIt())
}  
   
 
 

错误消息: 第29行:不能将MI文字(MI类型)用作字段值中的MyInter类型: MI不实现MyInter(缺少DoubleIt方法) )

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doujiu8479
    doujiu8479 2016-05-29 08:06
    已采纳

    In your code MI is a new type which doesn't carry over the methods from the original type. The DoubleIt method really isn't available:

    e2 := MI{12}
    fmt.Printf("%d
    ", e2.DoubleIt())
    
    e2.DoubleIt undefined (type MI has no field or method DoubleIt)
    

    An alternative if you want to carry over the methods would be to embed MyInt:

    type MI struct {
        MyInt
    }
    

    Then you can say:

    e2 := MI{MyInt{12}}
    fmt.Printf("%d
    ", e2.DoubleIt())
    

    From the spec:

    A type may have a method set associated with it. The method set of any other type T consists of all methods declared with receiver type T. Further rules apply to structs containing anonymous fields, as described in the section on struct types. Any other type has an empty method set.

    点赞 评论

相关推荐