go 中使用接口变量调用接收指针类型的方法
在 go 中,我们经常会遇到一种情况:需要使用接口变量调用接收指针类型的方法。这种情况下,编译器会报一个错误,提示我们无法直接用接口变量调用接收指针类型的方法。
要解决这个问题,可以通过以下两种方法:
package main import "fmt" type printer interface { print() } type foo struct { i int } func (f *foo) print() { f.i = 2 fmt.println(f) } func main() { f1 := foo{} var f2 any = f1 if _, ok := f2.(printer); ok { fmt.println("ok") } (*f2.(*foo)).print() // 显式转换接口变量为指针类型 fmt.println(f1) }
package main import "fmt" type Printer interface { print() } type Foo struct { i int } func (f *Foo) print() { f.i = 2 fmt.Println(f) } func main() { f1 := Foo{} var f2 any = f1 if _, ok := f2.(Printer); ok { fmt.Println("OK") } f2 = &f1 // 隐式转换接口变量为指针类型 f2.(Printer).print() fmt.Println(f1) }
那么,从哪个版本开始 go 支持这种方法调用的转换呢?
答案是:任何版本都可以。
需要注意的是,这里所说的「转换」不是指显式转换(如 (*f2.(*foo))),而是指隐式转换。在 go 中,只要接口变量的可寻址性与方法接收器的可寻址性相同,编译器就能自动进行隐式转换。
因此,在使用接口变量调用接收指针类型的方法时,如果接口变量的可寻址性是 可寻址的,那么编译器就能自动进行隐式转换,无需显式转换。
以上就是Go 接口变量如何调用接收指针类型的方法?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号