go - Golang - How to initialize a list of objects given only an interface sample? -


i'm writing database interface in google go. takes encoding.binarymarshaler objects save , saves them []byte slices, , loads data encoding.binaryunmarshaler return it:

func (db *db) get(bucket []byte, key []byte, destination encoding.binaryunmarshaler) (encoding.binaryunmarshaler, error) { 

i want implement being able load arbitrary length slice of encoding.binaryunmarshalers in 1 go (for example "load data bucket x"). want function able load number of data objects without knowing beforehand how many objects loaded, don't expect final user pass me slice filled. instead, take encoding.binaryunmarshaler sample object know structures i'm dealing with:

func (db *db) getall(bucket []byte, sample encoding.binaryunmarshaler) ([]encoding.binaryunmarshaler, error) { 

the problem ran while coding this, i'm not sure how initialize new instances of given object, since don't know object dealing with, interface conforms to. tried doing was:

tmp:=new(reflect.typeof(sample)) 

but caused error.

how can create new object in go without knowing structure is, having example object instead?

you have use reflect.new along reflect.typeof:

tmp := reflect.new(reflect.typeof(sample)) 

http://play.golang.org/p/-ujqwtrzap


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -