go - Runtime structure using reflection -
assume have data model written in sort of yaml file.
schema: human type: object properties: name: type: string surname: type: string
i parse it, , generate structure:
type human struct { name string `db:"name"` surname string `db:"surname"` }
is possible generate runtime go struct using reflection?
yes, can reflect.structof
:
stype := reflect.structof([]reflect.structfield{ {name: "name", type: stringtype, tag: reflect.structtag(`db:"name" json:"name"`)}, {name: "surname", type: stringtype, tag: reflect.structtag(`db:"surname" json:"surname"`)}, }) sv := reflect.new(stype) svi := sv.interface() b, err := json.marshal(svi) fmt.printf("%s %v", b, err)
prints
{"name":"","surname":""} <nil>
playground: https://play.golang.org/p/u4n3bbj5n8.
but others have said, it's better generate code. reflection kinda wonky @ times, , requires lot of precision when using it.
Comments
Post a Comment