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.
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
}
// .......
}
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.