gpt4 book ai didi

go - 不同类型的相同方法并在 Go 中返回不同的类型值

转载 作者:数据小太阳 更新时间:2023-10-29 03:13:38 25 4
gpt4 key购买 nike

我见过一些类似的问题( Same method on different array types in Go )

但在我的例子中,我的函数不返回相同的类型。

你能把下面的代码写得更简单点吗?

package main

import (
"encoding/json"
"fmt"
)

type A struct {
Name string `json:"name"`
Age int `json:"age"`
}

type B struct {
Name string `json:"name"`
Age int `json:"age"`
Address string `json:address`
}

func UnmarshalA(b []byte) *A {
var t *A
_ = json.Unmarshal(b, &t)
return t
}

func UnmarshalB(b []byte) *B {
var t *B
_ = json.Unmarshal(b, &t)
return t
}

func main() {
a := []byte(`{"name": "aaaa", "age": 1}`)
unmarshal_a := UnmarshalA(a)
fmt.Println(unmarshal_a.Name)

b := []byte(`{"name": "bbbb", "age": 2, "address": "b@example.com"}`)
unmarshal_b := UnmarshalB(b)
fmt.Println(unmarshal_b.Name)
}

// aaaa
// bbbb

https://play.golang.org/p/PF0UgkbSvk

最佳答案

您有几个选择。

  1. 不要费心使用 UnmarshalAUnmarshalB。它们实际上并没有做太多事情,而您实际上只是抽象出一行……var t *A

  2. 如果您实际上不需要 AB 结构,而只是希望以您可以使用的方式表示 JSON 字符串的内容,您可以直接解码到 map[string]interface{}

例如

package main

import (
"encoding/json"
"fmt"
)

func UnmarshalAny(b []byte) map[string]interface{} {
var t = make(map[string]interface{})
_ = json.Unmarshal(b, &t)
return t
}

func main() {
a := []byte(`{"name": "aaaa", "age": 1}`)
unmarshal_a := UnmarshalAny(a)

b := []byte(`{"name": "bbbb", "age": 2, "address": "b@example.com"}`)
unmarshal_b := UnmarshalAny(b)

// Accessed like this...
fmt.Println(unmarshal_a["name"])
fmt.Println(unmarshal_b["name"])
}

https://play.golang.org/p/KaxBlNsCDR

如果你想通过引用传递数据,那么你可以把它改成这样:

package main

import (
"encoding/json"
"fmt"
)

func UnmarshalAny(b []byte) *map[string]interface{} {
var t = make(map[string]interface{})
_ = json.Unmarshal(b, &t)
return &t
}

func main() {
a := []byte(`{"name": "aaaa", "age": 1}`)
unmarshal_a := UnmarshalAny(a)

b := []byte(`{"name": "bbbb", "age": 2, "address": "b@example.com"}`)
unmarshal_b := UnmarshalAny(b)

// Accessed like this...
fmt.Println((*unmarshal_a)["name"])
fmt.Println((*unmarshal_b)["name"])
}

https://play.golang.org/p/AXKYCCMJQU

关于go - 不同类型的相同方法并在 Go 中返回不同的类型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43909930/

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