gpt4 book ai didi

pointers - Go中的通用解码

转载 作者:行者123 更新时间:2023-12-01 22:03:41 26 4
gpt4 key购买 nike

我试图弄清楚是否有一种方法可以仅使用字符串和预期的类型将JSON字符串解编为特定的结构。到目前为止,这是我想出的。
代码

package main

import (
"encoding/json"
"fmt"
"reflect"
)

type Person struct {
Name string `json:"name"`
}

func genericUnmarshal(jsonString string, t reflect.Type) interface{} {
p := reflect.New(t)
result := p.Interface()
json.Unmarshal([]byte(jsonString), &result)
return result
}

func main() {
jsonData := "{\"name\":\"John\"}"
unmarshalledPerson := genericUnmarshal(jsonData, reflect.TypeOf(Person{}))

person := Person{Name: "John"}
fmt.Printf("struct value: %+v type: %+v\n", person, reflect.TypeOf(person))
fmt.Printf("unmarshalled value: %+v type: %+v\n", unmarshalledPerson, reflect.TypeOf(unmarshalledPerson))
fmt.Printf("are variables equal: %v\n", reflect.DeepEqual(unmarshalledPerson, person))
}
退货
struct value: {Name:John} type: main.Person
unmarshalled value: &{Name:John} type: *main.Person
are variables equal: false
方法 genericUnmarshal返回指向该类型的指针。
我的问题:有没有办法将未编码的值更改为结构(即 Person)而不是指针,以便 reflect.DeepEqual(unmarshalledPerson, person)返回 true

最佳答案

您可以比较人员指针,因为 reflect.DeepEqual() 也接受(深度)相等的指针值:

Pointer values are deeply equal if they are equal using Go's == operator or if they point to deeply equal values.


因此,只需:
fmt.Printf("are variables equal: %v\n",
reflect.DeepEqual(unmarshalledPerson, &person))
或取消引用包裹在 *Person中的 unmarshalledPerson指针,以便获得 Person结构:
fmt.Printf("are variables equal: %v\n",
reflect.DeepEqual(*unmarshalledPerson.(*Person), person))
两者都打印 true(在 Go Playground上尝试):
are variables equal: true
are variables equal: true
还要注意,对于您的“简单”结构,可以使用简单的 ==比较:
*unmarshalledPerson.(*Person) == person
如果添加其他字段(如指针,结构,映射等),则不会是这种情况。

关于pointers - Go中的通用解码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63263179/

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