Golang方法接收器

时间:2017-01-11 01:27:36

标签: go interface

根据this question,golang会同时生成type-receiver methodpoint-receiver method,这意味着下面的代码将正常运行,并且值会意外地发生变化。

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

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

我认为这对我来说是可以接受的。但是当这与界面混合时,事情就出错了。

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
}
它说:

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

为什么会发生这种情况?

Golang如何实际处理方法调用?

2 个答案:

答案 0 :(得分:1)

当你说:

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

这意味着接口Modifiable由类型*Test实现,即测试指针

在哪里

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

表示接口由类型Test

实现

结论是:一种类型和指向该类型的指针是两种不同的类型。

答案 1 :(得分:0)

如果你想使用一个有指针接收器的方法。这意味着你必须传递地址值。

这是一个例子:

package main

import "fmt"

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
    a.modify()
    fmt.Println(a)
}

总之,只要在方法中创建指针接收器,接口就会接受地址值。

相关问题