在Go语言中,是否可以动态地引用一个包的属性?

huangapple go评论79阅读模式
英文:

Is it possible to dynamically refer to a package property in Go?

问题

我主要是一个PHP开发者,最近开始研究Go语言。在PHP中,我可以做这样的事情:

<?php

class TestClass {
    public function testMethod() {
        echo "Hello!\n";
    }
}

$obj = new TestClass();
$method_name = "testMethod";
$obj->{$method_name}();

?>

输出结果为:Hello!

我知道以下内容并不是一个完美的比较,因为Go语言没有类,但我想知道在Go语言中是否可以通过导出模块的属性来实现类似的功能。例如,像这样的代码(我知道这不是有效的Go代码):

package main

import "fmt"

func main() {
    name := "Println"
    fmt[name]("Hello!")
}

这种方式有可能吗?如何实现类似的功能?谢谢。

编辑:将“模块”更改为“包”,因为这是我在Go语言中所指的正确名称

英文:

I'm primarily a PHP developer, and recently I started looking into Go. In PHP, I can do something like this:

&lt;?php

class TestClass {
	public function testMethod() {
		echo &quot;Hello!\n&quot;;
	}
}

$obj = new TestClass();
$method_name = &quot;testMethod&quot;;
$obj-&gt;{$method_name}();

?&gt;

The output being: Hello!.

I understand that the following is not a perfect comparison, since Go does not have classes, but I'm wondering if I can do something similar with exported properties of modules in Go. For example something like this (I understand that this is not valid Go code):

package main

import &quot;fmt&quot;

func main() {
	name := &quot;Println&quot;
	fmt[name](&quot;Hello!&quot;)
}

Is this in anyway possible? How can something similar be accomplished? Thank you.

Edit: Changed "module" to "package", since this is the proper name for what I was referring to in Go

答案1

得分: 5

package main

import (
"fmt"
"reflect"
)

type sayer struct {
said int
}

func (s *sayer) SayHello() {
fmt.Println("Hello")
}

func main() {
s := &sayer{}
cmd := "SayHello"
reflect.ValueOf(s).MethodByName(cmd).Call(nil)
}

英文:

I'm guessing you're looking for "reflection".

package main

import (
	&quot;fmt&quot;
	&quot;reflect&quot;
)

type sayer struct {
	said int
}

func (s *sayer) SayHello() {
	fmt.Println(&quot;Hello&quot;)
}

func main() {
	s := &amp;sayer{}
	cmd := &quot;SayHello&quot;
	reflect.ValueOf(s).MethodByName(cmd).Call(nil)
}

答案2

得分: 3

package main

import "fmt"

func main() {
m := map[string]func(va ...interface{}) (int, error){"Println": fmt.Println}
m["Println"]("Hello, playground")
}

英文:

Have no idea what is meant by 'module properties' (no such thing is known by the Go specs). Only guessing:

package main

import &quot;fmt&quot;

func main() {
        m := map[string]func(va ...interface{}) (int, error){&quot;Println&quot;: fmt.Println}
        m[&quot;Println&quot;](&quot;Hello, playground&quot;)
}

(Also here)


Output

Hello, playground

huangapple
  • 本文由 发表于 2013年3月8日 14:30:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/15288085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定