英文:
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:
<?php
class TestClass {
public function testMethod() {
echo "Hello!\n";
}
}
$obj = new TestClass();
$method_name = "testMethod";
$obj->{$method_name}();
?>
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 "fmt"
func main() {
name := "Println"
fmt[name]("Hello!")
}
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 (
"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)
}
答案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 "fmt"
func main() {
m := map[string]func(va ...interface{}) (int, error){"Println": fmt.Println}
m["Println"]("Hello, playground")
}
(Also here)
Output
Hello, playground
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论