go - 如何向 Go 中的现有类型添加新方法?

标签 go extension-methods

我想在 gorilla/mux Route 和 Router 类型上添加一个方便的 util 方法:

package util

import(
    "net/http"
    "github.com/0xor1/gorillaseed/src/server/lib/mux"
)

func (r *mux.Route) Subroute(tpl string, h http.Handler) *mux.Route{
    return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h)
}

func (r *mux.Router) Subroute(tpl string, h http.Handler) *mux.Route{
    return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h)
}

但编译器会通知我

Cannot define new methods on non-local type mux.Router

那么我该如何实现呢?我是否创建一个具有匿名 mux.Route 和 mux.Router 字段的新结构类型?还是别的什么?

最佳答案

正如编译器所提到的,您不能在另一个包中扩展现有类型。您可以定义自己的别名或子包,如下所示:

type MyRouter mux.Router

func (m *MyRouter) F() { ... }

或通过嵌入原始路由器:

type MyRouter struct {
    *mux.Router
}

func (m *MyRouter) F() { ... }

...
r := &MyRouter{router}
r.F()

关于go - 如何向 Go 中的现有类型添加新方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28800672/

相关文章:

dictionary - 如何使用反射反转 map

angular - API调用后如何重定向

c# - 我可以扩展 LINQ-to-SQL 支持的运算符吗?

c# - TryParse 其他类型

c# - 我可以向现有静态类添加扩展方法吗?

templates - 模板对象字段强制执行

去 GC 奇怪的行为

没有键的JSON字符串数组进入GoLang结构

c# - 在 C# 中调用扩展方法的不同方式

c# - 如何在 VB 代码中调用 C# 扩展方法