动态初始化结构

user99999:

我有几个结构,例如:

type SomeObject struct {
   sample int
}

我想sample根据我在请求正文中得到的内容来填充变量。为此,我想创建一个函数,将请求主体作为字符串传递给它,在其中创建一个空结构,用数据填充该结构,返回它,并用此替换所选的结构。

我该怎么做呢?我从函数返回什么?有没有办法做到这一点?

传福音:

如果要处理多种类型,则应使方法返回interface{}对于所有适用的类型,请创建一个便捷方法,例如;

func NewSomeObject(reqBody string) *SomeObject {
     return &SomeObject{sample:reqBody}
}

它需要一个字符串并返回该类型的新实例,并且该字段设置为传入的值。您的问题是缺少有关如何确定应实例化哪种类型的信息,但假设您有几个实例,则可能需要/ else或接收请求正文的方法中的一个开关,以便给出一个非常模糊的示例,它类似于:

func ProcessRequest(reqBody string) interface{} {
      if someCondition {
           return NewSomeObject(reqBody)
      } else if otherCondition {
           return NewSomeOtherObject(reqBody)
      } // potentially several other statements like this
      return nil // catch all, if no conditions match
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章