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

标签 go extension-methods

我想在gorilla/mux路由和路由器类型上添加一个便捷的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)
}

但是编译器告诉我

无法在非本地类型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/63881662/

相关文章:

c# - 静态方法声明中的 "this"是什么意思?

linux - 将 os.Signal 转换为字符串以便能够将其打印在文件中

go - Kubernetes客户端找不到模块

c# - ASP.NET MVC : 'Extend' Html. TextBox 有条件地具有 CSS 值?

swift - 从另一个类重置扩展文件 userdefault

ios - 如何在类扩展中添加静态(存储)属性以创建单例? ( swift )

google-app-engine - 静态页面在 Google App Engine 中返回 404

Golang 溢出 int64

sql - 预期 slice 但得到界面

asp.net-mvc-3 - 如何扩展 MVC3 Label 和 LabelFor HTML helpers?