如何在Golang中使用字符串新建对象 [英] How to new an object with string in Golang

查看:82
本文介绍了如何在Golang中使用字符串新建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我只有一个字符串类型的对象时,该如何创建一个对象? 我正在寻找类似的东西:

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"

当使用不同的ORM库(例如GORP和GORM)时,这将非常有用和方便.

It will be really helpful and convenience with this when using different ORM library like GORP and GORM.

可以在Golang中做到吗?

Is it possible to do it in Golang?

推荐答案

否...

好吧,答案是是,但是",但是很大. 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)
    }
}

这篇关于如何在Golang中使用字符串新建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆