0

Not in golang, we can instantiate class dynamically by class name as

PHP

<?php
class MyKlass {
    public $prop = "foo";
    public function meth() {
        echo "This is my method\n";
        echo "This.prop = {$this->prop}";
    }
}
$class_name = "MyKlass";
$k = new $class_name;
$k->meth();

Python

class MyKlass:
    def __init__(self):
        self.prop = "buz"
    def meth(self):
        print("This prop is " + self.prop)
modules = {
    "MyKlass":MyKlass
}
class_name = "MyKlass"
k = modules[class_name]()
k.meth()

So in golang, how to instantiate struct by using struct name, which is string type?

otiai10
  • 4,289
  • 5
  • 38
  • 50
  • As in other languages, this is called "reflection" and there's a package for that : http://golang.org/pkg/reflect/ – Denys Séguret May 06 '14 at 05:47
  • 1
    Thanks! It is duplicated by this question http://stackoverflow.com/questions/23030884/is-there-a-way-to-create-an-instance-of-a-struct-from-a-string. – otiai10 May 07 '14 at 00:28
  • 1
    This is the obligatory reminder that reflection is much, much slower than using interfaces or repeating some boilerplate code, and tends to make the code much simpler as well. You're better off adapting your program's structure to the differently-structured language than trying to translate your PHP or Python directly. – twotwotwo May 07 '14 at 17:42
  • 1
    Ack, previous comment meant to say interfaces make the code _simpler_ than reflection. For instance, if your `meth` was `HandleRequest(Request, Response)`, you could make that the sole method in a `RequestHandler` [interface](http://golang.org/doc/effective_go.html#interfaces_and_types), and your `modules` dictionary could map strings to functions that make RequestHandlers. Doesn't require a way to create objects using a string class name directly. – twotwotwo May 07 '14 at 17:50

0 Answers0