function - 传递对象并将其捕获在接口(interface)中时无法访问函数{}

标签 function interface go

这是我正在尝试做的事情:

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)))
    }
}

知道为什么我不能在我的 productManager 对象上调用 List() 函数吗?我可以看到类型的功能,甚至可以在 index() 处理程序中获得正确的类型名称。

最佳答案

非常简单:rm 是一个空接口(interface)变量,因此它没有任何方法,这正是 interface{} 的意思:没有方法。如果您知道 rm 的动态类型是 *ProductManager,您可以键入断言它(但是您可以传递一个 *ProductManager)也许您从长远来看,必须在 rm 上键入 switch。 (顺便说一句:使用 interface{} 几乎总是一个坏主意。)

关于function - 传递对象并将其捕获在接口(interface)中时无法访问函数{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23785225/

相关文章:

javascript 代码只能在函数之外工作——为什么?

c# - 为什么 IsEnabled 是 ILogger 接口(interface)的一部分?

php - Laravel 中的仓库和接口(interface)有什么用?

java - 使用带有 List 作为方法参数的 java 泛型的编译器错误并抛出泛型异常

recursion - 在 Go 中拥有带递归的 len 函数

html - 我无法在 HTML 上查看所有 MySQL 表数据

go - 如何在旅途中解决螺旋矩阵

function - 在 Haskell 中用另一个函数作为参数提升一个函数

C++函数问题

python - 在Python中创建一系列弧度值