-2

I have a struct as follows

type MyStruct {
   EmbeddedFooBar
}

func (m *MyStruct) Foo(b *http.Request) {
   // Doing something
} 

func fn(args ...interfaces) {
    // It's here I want to get my struct back and run the "Get" method
    // Please keep in mind I am too pass a pointer param into the struct method
    strt := args[0]

    ....
    get struct back to static data type MyStruct
    and run "Get()", dont mind how/where I will get *http.Request to pass, assume I can
    ....

    strt.Get(*http.Request)
}

func main() {
    a := &MyStruct{}
    fn(a)
}

I am passing the struct above to a variadic function fn that expects ...interfaces{} (thus any type can satisfy the params)

Inside the function fn I want to get back my struct MyStruct to it's data type and value and run it's method Get that can also accept receivers such as *http.Request

How do I get My Struct back from the interface arg[0] and run the method Get of the struct with the ability of passing a pointer.

TheHippo
  • 61,720
  • 15
  • 75
  • 100
Knights
  • 1,467
  • 1
  • 16
  • 24
  • 1
    See: http://stackoverflow.com/questions/14289256/cannot-convert-data-type-interface-to-type-string-need-type-assertion –  Jul 14 '15 at 23:41

2 Answers2

1

What you want is Type Assertion. Solution could something like this:

func fn(args ...interfaces) {
    if strt, ok := args[0].(*MyStruct); ok {
        // use struct
    } else {
        // something went wrong
    }
    // .......
}
TheHippo
  • 61,720
  • 15
  • 75
  • 100
  • What if the struct was passed from another package, and you do not know which struct was passed? Eg. Beego frameworks allow one to pass your own struct, how does it figure our ur methods, and struct in the 1st place – Knights Jul 15 '15 at 07:53
0

It sounds like what you want here is a specific interface, specifically one that has a Get method that accepts a pointer to an http.Request.

For example:

type Getter interface {
    Get(*http.Request)
}

func fn(getters ...Getter) {
    getter := getters[0]
    getter.Get(*http.Request)
}

func main() {
    a := &MyStruct{}
    fn(a)
}

This allows the compiler to check that the arguments to fn have exactly the methods you need, but it doesn't need to know anything else about the type. Read more about interfaces here.

ford
  • 10,687
  • 3
  • 47
  • 54