Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

go - Reflection: Struct by string

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...