Go语言中,一般方法接收者和接口方法接收者有一定区别。

在一般方法中
若定义的接收者是值,可以使用值或者指针进行调用;
若定义的接收者是指针,可以使用值或者指针进行调用。

在接口方法中
若定义的接收者是值,则既可以用接口值调用,也可以用接口指针调用;
若定义的接收者是指针,则只能用接口指针调用,不能用接口值调用。

如下例:

package main

import "fmt"

type T struct {
    S string
}

type I interface {
    A()
    B()
}

func (t T) A() {
    fmt.Println(t.S)
}

func (t *T) B() {
    fmt.Println(t.S)
}

func main() {
    t := T{"normal method"}
    pt := &t
    t.A()
    t.B()
    pt.A()
    pt.B()

    //var i I = T{"interface method"}
    var i I = &T{"interface method"}
    i.A()
    i.B()
}

若使用
var i I = &T{"interface method"}
则可以执行。

若使用
var i I = T{"interface method"}
则报错:

./prog.go:30:6: cannot use T{...} (type T) as type I in assignment:
    T does not implement I (B method has pointer receiver)

提示B方法用的是指针接收者(pointer receiver),无法被接口值调用。

那么,为何会有这样的差异?


cainmusic
10 声望0 粉丝