How to new an object with string in Golang

前端 未结 2 1050
忘掉有多难
忘掉有多难 2021-01-25 11:25

How can I create an object when I am only having its type in string? I am looking for something like:

type someStruct struct {}

resultObject := new \"someStruct         


        
2条回答
  •  灰色年华
    2021-01-25 11:44

    No...

    Well, the answer is "yes, but" and it's a big but. There's no central registry of struct names in Go. You're not going to get a nice, clean standard library function called StructFromName(string) which is probably what you were hoping for.

    Instead, you have to write that mapping yourself, something like

    func StringToStruct(name string) (interface{}, error) {
        switch name {
        case "SomeStruct":
            return SomeStruct{}, nil
        case "SomeOtherStruct":
            return SomeOtherStruct{}, nil
        case "subpackage.Struct":
            return subpackage.Struct{}, nil
        default:
            return nil, fmt.Errorf("%s is not a known struct name", name)
        }
    }
    

提交回复
热议问题