0

I have the below interface that implements a simpler Active Record Like implementation for my persistent layer.

type DBInterface interface {
  FindAll(collection []byte) map[string]string
  FindOne(collection []byte, id int) map[string]string
  Destroy(collection []byte, id int) bool
  Update(collection []byte, obj map[string]string ) map[string]string
  Create(collection []byte, obj map[string]string) map[string]string
}

The application has different collection's that it talks to and different corresponding models. I need to be able to pass in a dynamic Struct , instead of a map for the value obj ( ie. Update , Create Signatures )

I can't seem to understand how to use reflection to resolve the Struct , any guidance would help.

More details on what I am trying explain :

Consider the below snippet from mgo example from https://labix.org/mgo

    err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
               &Person{"Cla", "+55 53 8402 8510"})

When we insert data to the collection , we do a &Person I want to be able to pass in this bit &Person{"Ale", "+55 53 8116 9639"} but the method receiving the would only know it in the Run time. Because it could be a Person , Car , Book etc Struct depending on the func calling the method

4
  • 3
    I don't understand what your mean by use reflection to resolve the Struct; can you show what you're trying to achieve? Commented Aug 10, 2015 at 15:52
  • @JimB Added a trivial example on what I am trying to achieve Commented Aug 10, 2015 at 18:00
  • If you just want to pass it into mgo, you don't need to do the reflection, just give the interface to c.Insert. Do you need to operate on these structs yourself too? Commented Aug 10, 2015 at 18:50
  • Well , I just wanted to have a interface between my persistent layer and the Repositories so that I can change the persistent layer by re-implementing the Interface to support a different Persistent layer without having to change a lot of my other code. Ideally I would have to operate on the structs as well Commented Aug 11, 2015 at 3:34

1 Answer 1

1
  1. Declare your obj type as interface{}

         Update(collection []byte, obj interface{} ) map[string]string  
    
  2. Now you can pass Person,Book,Car etc to this function as obj.

  3. Use a type switch inside Update function for each actual struct

        switch t := obj.(type){
        case Car://Handle Car type
        case Perosn:
        case Book:
                      }
    

    Structs needs to be decided at compile time.No dynamic types in Go.Even interfaces are static types.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.