且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Golang中使用字符串新建对象

更新时间:2022-06-19 23:42:27

否...

好吧,答案是是,但是",但是很大. Go中没有结构名称的中间注册表.您不会获得一个很好的,干净的标准库函数,称为StructFromName(string),这可能正是您所希望的.

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)
    }
}