Answer the question
In order to leave comments, you need to log in
How to "override" struct fields in Golang?
hello i have structure
DefaultResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Datas []Data`json:"datas"`
}
Data struct {
ID int64
Name string
}
Data struct {
ID int64
Value int64
}
Answer the question
In order to leave comments, you need to log in
In Go this is done with composition
https://play.golang.org/p/9ThbqjKzytZ
package main
import (
"encoding/json"
"fmt"
)
type Data1 struct {
SomeField string `json:"some_field"`
}
type Data2 struct {
SomeOtherField string `json:"some_other_field"`
}
type DefaultResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
type Response1 struct {
DefaultResponse
Datas []Data1 `json:"datas"`
}
type Response2 struct {
DefaultResponse
Datas []Data2 `json:"datas"`
}
func main() {
json1 := `{"code":123,"msg":"test","datas":[{"some_field":"test field data"}]}`
json2 := `{"code":456,"msg":"test2","datas":[{"some_other_field":"other test field data"}]}`
var res1 Response1
var res2 Response2
json.Unmarshal([]byte(json1), &res1)
json.Unmarshal([]byte(json2), &res2)
fmt.Printf("%+v\n", res1)
fmt.Printf("%+v\n", res2)
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question