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個贊
我不知道你到底想建立什么,但會嘗試根據我的理解提供一些見解。
如果您嘗試對兩個結構使用相同的解析器,則它們可能有一些共同點??赡芩鼈儽灰黄鹩糜谀鷳贸绦虻哪承┯美?/p>
因此,如果它們一起使用,它們應該實現一些接口,這些接口表示這些結構具有共同的特征集(可能與數據解析有關,也可能不相關)。
而且,正如你所說,你事先知道你需要什么類型的結構,所以這樣做應該很容易:
//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 關注
- 129 瀏覽
添加回答
舉報