G
G
Georgy Pugachev2019-05-24 18:05:00
go
Georgy Pugachev, 2019-05-24 18:05:00

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"` 
  }

and there are many separate packages where I want to override the Data structure while keeping the DefaultResponse.
For example, in one package I need:
Data struct {
    ID    int64
    Name  string
  }

and in another
Data struct {
    ID    int64
    Value  int64
  }

How to implement it?
UPD: The DefaultResponse common for all packages is needed so as not to drag the same functionality associated with it into all packages.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2019-05-24
@gvpugachev

In Go this is done with composition
https://play.golang.org/p/9ThbqjKzytZ

The code
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 question

Ask a Question

731 491 924 answers to any question