1

Let's assume I have this struct with a method:

package main

import (
    "fmt"
    "reflect"
)

type MyStruct struct {
}

func (a *MyStruct) AAction() {
    fmt.Println("Hello a")
}

Now, if I want to call the method "AAction" by string, I can use reflection (this works):

func main() {
    reflect.New(reflect.TypeOf(MyStruct{})).MethodByName("AAction").Call([]reflect.Value{})
}

The problem is, that I don't want to use MyStruct{} as an expression, but as a string. Of course this doesn't work:

func main() {
    theStruct := "MyStruct"
    theAction := "AAction"
    reflect.New(reflect.TypeOf(theStruct)).MethodByName(theAction).Call([]reflect.Value{})
}

because reflect.Typeof(theStruct) would be a string. I tried reading through the documentation, sadly, I can't find anything very useful.

I found this similar question: Call a Struct and its Method by name in Go?
Under the accepted question, the OP asks:

The issue in my case Is I cant not declare t is typed T, its must be some how I can declare t typed T by the name of T is string "T"

which gets answered by

[...] I would suggest to match the name against the string "T" somewhere in your code [...]

which doesn't solve the problem, as I would still need to call MyStruct{} somewhere.

The question is: is there any way to use a struct by giving the name as a string? (without manually mapping the the name of the struct to the struct)

Working version with using reflect.TypeOf(MyStruct{}): PlayGround
Not working version, obviously calling the method on a string: PlayGround

2
  • 2
    Have a registry where you register each type by its name. Then consult the registry with that name and pull out whatever you registered. A bit how image decoders register them in the image package. Don't do reflection. Commented Apr 5, 2016 at 12:18
  • @Volker I'm aware that I shouldn't, but the question was: could I do reflection? Commented Apr 5, 2016 at 12:56

1 Answer 1

3

Sorry, you can't. The answer is: you could not. There is no builtin or pre-initialized registry of type names.

To get started with reflection (reflect package), you need a value (of the type in question). Based on a string (string name of the type), you can't acquire a value of that type, so you can't get started.

If you do want to do what you want only by a string type name, you need to build your own "registry" prior to doing what you want.

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry that it took me long to accept the answer. I was hoping for someone to shout "NOPE"

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.