duan0414 2017-01-11 01:27
浏览 106
已采纳

Golang方法接收器

According this question, golang will generate both type-receiver method and point-receiver method, which means the code below will work correctly and the value will change unexpectedly.

func (test *Test) modify() {
    test.a++
}

func main() {
    test := Test{10}
    fmt.Println(test)
    test.modify()
    fmt.Println(test)
}

I think it's acceptable to me. But when this mixes with interface, thing goes wrong.

type Modifiable interface {
    modify()
}

type Test struct {
    a int
}

func (test *Test) modify() {
    test.a++
}

func main() {
    test := Test{10}
    fmt.Println(test)
    test.modify()
    fmt.Println(test)

    var a Modifiable

    a = test
}

it said:

Test does not implement Modifiable (modify method has pointer receiver)

Why will this happen ?

And how golang actually handle method call ?

  • 写回答

2条回答 默认 最新

  • dongtuoleng8624 2017-01-11 04:40
    关注

    When you said:

    func (test *Test) modify() {
        test.a++
    }
    

    It means the interface Modifiable is implemented by the type *Test aka the Pointer to Test

    Where as

    func (test Test) modify() {
            test.a++
    }
    

    means that the interface is implemented by the type Test

    Conclusion is: A type and a pointer to that type are 2 different types.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏