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.binaryunmarshaler
s 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))
Comments
Post a Comment