How to add new methods to an existing type in Go?

Daniel Robinson picture Daniel Robinson · Mar 2, 2015 · Viewed 71.1k times · Source

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?

Answer

jimt picture jimt · Mar 2, 2015

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