0

I'm writing a database interface in Google Go. It takes encoding.BinaryMarshaler objects to save and saves them as []byte slices, and it loads data into encoding.BinaryUnmarshaler to return it:

func (db *DB) Get(bucket []byte, key []byte, destination encoding.BinaryUnmarshaler) (encoding.BinaryUnmarshaler, error) {

I want to implement being able to load an arbitrary length slice of encoding.BinaryUnmarshalers in one go (for example "load all data from a bucket X"). I want the function to be able to load any number of data objects without knowing beforehand how many objects are to be loaded, so I don't expect the final user to pass me a slice to be filled. Instead, I take a encoding.BinaryUnmarshaler sample object to know what structures I'm dealing with:

func (db *DB) GetAll(bucket []byte, sample encoding.BinaryUnmarshaler) ([]encoding.BinaryUnmarshaler, error) {

The problem I ran into while coding this, is that I'm not sure how to initialize new instances of a given object, since I don't know what object I am dealing with, only what interface it conforms to. What I tried doing was:

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

but that just caused an error.

How can I create a new object in go without knowing what structure it is, having an example object instead?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
ThePiachu
  • 8,695
  • 17
  • 65
  • 94
  • If you "don't know what object ... [you are] dealing with" then your're lost. That's something you need to know: Transmit, Take a look at how `gob` does it. – Volker Oct 02 '15 at 22:26
  • 1
    Possible duplicate of [New instance of struct from the type at runtime in GO](https://stackoverflow.com/questions/33469177/new-instance-of-struct-from-the-type-at-runtime-in-go) – kenfire Dec 08 '17 at 08:50
  • @kenfire this question was asked a month before the other one ;) – ThePiachu Dec 10 '17 at 20:40
  • @ThePiachu Yes but you did not accept your answer so I couldn't do the other way :) – kenfire Dec 11 '17 at 08:24

1 Answers1

1

You would have to use reflect.New along with reflect.TypeOf:

tmp := reflect.New(reflect.TypeOf(sample))

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

dave
  • 62,300
  • 5
  • 72
  • 93