如何将新方法添加到现有类型中去? [英] How to add new methods to an existing type in go?

查看:128
本文介绍了如何将新方法添加到现有类型中去?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  package util $ b $我想为大猩猩/ mux路由和路由器类型添加一个便利的util方法: b 
进口(
净/ 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( (/)。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}
rF()


I want to add a convenience util method on to gorilla/mux Route and Router types:

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

but the compiler informs me

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

So how would I achieve this? Do I create a new struct type that has an anonymous mux.Route and mux.Router fields? Or something else?

解决方案

As the compiler mentions, you can't extend existing types in another package. You can define your own alias or sub-package as follows:

type MyRouter mux.Router

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

or by embedding the original router:

type MyRouter struct {
    *mux.Router
}

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

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

这篇关于如何将新方法添加到现有类型中去?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆