2 回答
TA贡献1828条经验 获得超3个赞
编写函数以获取指向结果的指针:
func parseAnything(body []byte, c interface{}) error {
return json.Unmarshal(body, c)
}
像这样使用它:
var p phoneStruct
if err := parseAnything(jsonPhone, &p); err != nil {
// handle error
}
// p has unmarshaled phone
var c carStruct
if err := parseAnything(jsonCar, &c); err != nil {
// handle error
}
// c has unmarshaled car
TA贡献1880条经验 获得超4个赞
我不知道你到底想建立什么,但会尝试根据我的理解提供一些见解。
如果您尝试对两个结构使用相同的解析器,则它们可能有一些共同点。可能它们被一起用于您应用程序的某些用例。
因此,如果它们一起使用,它们应该实现一些接口,这些接口表示这些结构具有共同的特征集(可能与数据解析有关,也可能不相关)。
而且,正如你所说,你事先知道你需要什么类型的结构,所以这样做应该很容易:
//The interface that represents what the structs have in common.
//I named it "Parser" because it's the info I have. It probably should have another (better) name
type Parser interface {
Parse([]byte) (Parser, error)
}
type Phone struct {
PhoneID string `json:"id"`
Carrier string `json:"carrier"`
}
type Car struct {
CarID string `json:"id"`
Model string `json:"model"`
}
func (p *Phone) Parse (body []byte) (Parser, error) {
err := json.Unmarshal(body, p)
return p, err
}
func (c *Car) Parse (body []byte) (Parser, error) {
err := json.Unmarshal(body, c)
return c, err
}
func main() {
c := Car{}
var jsonCar = `{
"id": "123",
"model": "Civic"
}`
res, _ := c.Parse([]byte(jsonCar))
fmt.Println(res)
p := Phone{}
var jsonPhone = `{
"id": "123",
"carrier": "Rogers"
}`
res, _ = p.Parse([]byte(jsonPhone))
fmt.Println(res)
}
- 2 回答
- 0 关注
- 169 浏览
添加回答
举报
