Here's what I'm trying to do:
package products
ProductManager struct {
products []*Product
index int64
}
func NewPM() *ProductManager {
return &ProductManager{}
}
func (p *ProductManager) List() []*Product {
return p.products
}
---
var productManager = products.NewPM()
func main() {
api := Api{}
api.Attach(productManager, "/products")
}
func (api Api) Attach(rm interface{}, route string) {
// Apply typical REST actions to Mux.
// ie: Product - to /products
mux.Get(route, http.HandlerFunc(index(rm)))
}
func index(rm interface{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// allRecords := rm.List() - DOESN'T WORK. No method found.
result := reflect.TypeOf(rm) // Works, shows me the correct type.
method := result.Method(0).Name // Works as well! Shows me a function on the type.
w.Write([]byte(fmt.Sprintf("%v", method)))
}
}
Any idea on why I can't call the List()
function on my productManager
object? I can see the Type's functions and even get the right Type name in the index()
handler.
Dead simple: rm
is an empty interface variable, so it does not have any methods, that's exactly what interface{}
means: No methods. If you know that rm
's dynamic type is *ProductManager
you can type assert it (but than you could pass a *ProductManager
) Maybe you'll have to type switch on rm
in the longer run. (BTW: using interface{}
is almost always a bad idea.)