gpt4 book ai didi

go - 在go中使用字符串通过名称实例化结构

转载 作者:IT王子 更新时间:2023-10-29 01:55:51 25 4
gpt4 key购买 nike

我正在尝试创建一个函数,它接受一个 []byte 和一个 interface{}(代表 struct)并返回作为 struct 类型传递给 funcinterface{}

像这样:

package main

import (

"encoding/json"

)


func UnmarshalFromJSONArray(sms []byte,tt string) (interface{}) {
var ts = new(tt)
err := json.Unmarshal(sms,&ts)
if(err != nil) {
fmt.Println(err)
}
return sms
}

所以该方法会像这样运行:

// let's say a struct has the following definition:

type MyStructType struct {
Id int
Name string
Desc string
}

// we can some how get its fully qualified class name (this may require reflection?) or pass it into the UnMarshal method direction some how.
mst := "package.MyStructType",

// and then assume a byte array ba that has JSON format for

ba := []byte(`{"Id":"3","Name":"Jack","Desc":"the man"}`)

stct := UnmarshalFromJSONArray(ba,mst)

MyStructureType out := stct

// leaving "stct" being the unmarshalled byte array which can be used like any other struct of type "MyStructureType"

关键是在解码之前我永远不需要知道 MyStructureType 的字段是什么。我只需要 struct 的名称和一些实例化方法,然后用与其字段匹配的 JSON 字节数组数据填充它。希望这是可能的(在使用反射的 Java 中这是微不足道的)。所以我想基本上根据名称解码一个匿名 struct 类型,而不需要知道它有哪些字段。

有什么建议吗?

最佳答案

简短的回答是这是不可能的。 Go 中没有字符串类型转换器。您可以创建一个字符串映射来反射(reflect)类型,但您需要提前知道可能的选项,或者您需要为调用者提供一种注册类型的方法(可能在 init 中)。

假设您已经找到一种将字符串解析为它的 reflect.Type 的方法,您可以简单地调用 reflect.New(typ).Interface() 来获取您需要传递给 json.Unmarshal() 的指针。

最好的答案是避免同时尝试这一切。在 Go 中编写地道的 Java 是不可能的。如果我对你的问题了解得更多,我可以给你一个更地道的 Go 解决方案。

关于go - 在go中使用字符串通过名称实例化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20916405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com