网络编程
位置:首页>> 网络编程>> Go语言>> Go 一般方法与接口方法接收者的差异详解

Go 一般方法与接口方法接收者的差异详解

作者:cainmusic  发布时间:2024-04-27 15:38:52 

标签:Go,接收差异,一般方法,接口方法

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),无法被接口值调用。

那么,为何会有这样的差异?更多关于Go 方法不同接收者差异的资料请关注asp之家其它相关文章!

来源:https://segmentfault.com/a/1190000041260070

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com