给定方法值,获取接收者对象 [英] Given a method value, get receiver object

查看:64
本文介绍了给定方法值,获取接收者对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Go中是否有一种方法可以从方法值中获取接收者对象?

Is there a way in Go, to get the receiver object from a method value?

例如,是否有任何这样的MagicFunc会使下面的程序从基础Foo实例中输出字符串my info.

For example, is there any such MagicFunc that would make the following program output the string my info from the underlying Foo instance.

package main

import "fmt"

type Foo struct {
    A string
}

func (foo *Foo) Bar() string {
    return "bar"
}

func MyFunc(val interface{}) {
    i := MagicFunc(val)
    f := i.(Foo)
    fmt.Println(f.A)
}

func main() {
    f := Foo{A: "my info"}
    MyFunc(f.Bar)
}

推荐答案

否,无法获取该方法的接收者实例.

No, it is not possible to get the method's receiver instance.

如果使用方法表达式而不是方法值,则最多可以得到接收者的类型,但这不会帮助您获取my info字符串.

The most you can get is the receiver's type if you use a method expression instead of method value but that won't help you get the my info string.

这篇关于给定方法值,获取接收者对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆