Skip to content

Instantly share code, notes, and snippets.

@buroz
Created November 25, 2020 10:11
Show Gist options
  • Save buroz/edef4c6a37878f9c77670df58debdea6 to your computer and use it in GitHub Desktop.
Save buroz/edef4c6a37878f9c77670df58debdea6 to your computer and use it in GitHub Desktop.
Generics in Golang
package main
import (
"encoding/json"
"fmt"
"io"
"os"
)
type Company struct {
Id int64 `json:"id"`
Status bool `json:"status"`
Name string `json:"name"`
}
func JsonUnmarshal(type T) (body []byte) (T, error) {
var res T
err := json.Unmarshal(body &res)
return res, err
}
type JsonDecoder (type T) struct {
d *json.Decoder
res T
}
func NewJsonDecoder(type T) (rd io.Reader) JsonDecoder(T) {
return JsonDecoder(T){
d: json.NewDecoder(rd),
}
}
func (this JsonDecoder(T)) Decode() (T, error) {
err := this.d.Decode(&this.res)
if err != nil {
var empty T
return empty, err
}
return this.res, err
}
func (this JsonDecoder(T)) Slice() ([]T, error) {
var results []T
for {
res, err := this.Decode()
if err == io.EOF {
return results, nil
} else if err != nil {
return nil, err
}
results = append(results, res)
}
return results, nil
}
func main() {
d := NewJsonDecoder(Company)(os.Stdin)
companies, _ := d.Slice()
for _, company := range companies {
fmt.Println(company.Name)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment