go - How do I pass in an interface{} to a function as a specific structure? -
i trying have generic routine handle messages between specific components. part of involves reading byte array , using json.marshal , json.unmarshal , calling callback.
i trying pass interface function expects specific structure, not know type of target structure. in code below, how function r() call function cb() , pass in correct data?
package main import ( "encoding/json" "fmt" "reflect" ) type bottom struct { foo string } func cb(b *bottom) { fmt.println("5. ", b) } func r(t interface{}, buf []byte) { _ = json.unmarshal(buf, &t) fmt.println("2. ", reflect.typeof(t)) fmt.println("3. ", t) cb(&t) } func main() { x := bottom{foo: "blah"} var y bottom buf, _ := json.marshal(x) fmt.println("1. ", x) r(&y, buf) }
you need use type assertion convert interface{}
type function requires. can add error checking appropriately handle case parameter can't typecast desired type.
see generic playground demonstrates solution: http://play.golang.org/p/nyeoavteea
in case, means
cb(&t.(bottom))
you can add error checking:
bottom, ok := t.(bottom) if !ok { // } cb(&bottom)
Comments
Post a Comment