{ Josh Rendek }

<3 Go & Kubernetes

This is useful if you’re building a generic library/package and want to let people pass in types and convert to them/return them.

 1package main
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"reflect"
 7)
 8
 9type Monkey struct {
10	Bananas int
11}
12
13func main() {
14	deliveryChan := make(chan interface{}, 1)
15	someWorker(&Monkey{}, deliveryChan)
16	monkey := <- deliveryChan
17	fmt.Printf("Monkey: %#v\n", monkey.(*Monkey))
18}
19
20func someWorker(inputType interface{}, deliveryChan chan interface{}) {
21	local := reflect.New(reflect.TypeOf(inputType).Elem()).Interface()
22	json.Unmarshal([]byte(`{"Bananas":20}`), local)
23	deliveryChan <- local
24}

Line 22 should be using whatever byte array your popping off a MQ or stream or something else to send back.

comments powered by Disqus