【发布时间】:2022-01-02 10:35:58
【问题描述】:
我正在研究一个关于编组的示例,并决定巧妙地使用它。希望我可以传递一个类似于json.Unmarshall 函数的通用接口引用,并通过输入而不是重复相同的代码来处理我的其他测试用例(是的,我来自Java)。相反,我得到了一个地图而不是一个结构。看来我也没有办法向下暗示这种结构的“类型”是什么。
问题:
- 我怎样才能找回适当的结构类型?
- 采用这种实用方法的方法是否合理?
代码:
//test 1 - simple dto
var country models.Country
var outCountry, errorCountry = attemptParse("Simple DTO", "./json/country.json", country)
fmt.Println("Return - ", outCountry, " - ", errorCountry)
...
func attemptParse(test string, dataFile string, v interface{}) (interface{}, error){
...
err := json.Unmarshal(data, &v)
if err != nil {
fmt.Println("Test - ", test, " - fail", err)
return nil, err
}
fmt.Println("Test - ", test, " - result:")
fmt.Println(v)
return v, nil
}
还尝试编组到nptr := reflect.New(reflect.TypeOf(v)),但这以我无法解析的地址结束。
输出:
Test - Simple DTO - start
Test - Simple DTO - result:
map[Capital:Washington DC Continent:North America Name:USA]
Return - map[Capital:Washington DC Continent:North America Name:USA] - <nil>
【问题讨论】:
-
将指针传递给
attemptParse:attemptParse("Simple DTO", "./json/country.json", &country)将指针值传递给Unmarshal:json.Unmarshal(data, v)。我正在写评论而不是答案,因为这个问题有很多重复项,但我目前找不到。
标签: go