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!
";
}
}
$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
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
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)
}