goextension-methods

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


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?


Solution

  • As the compiler mentions, you can't extend existing types in another package. You can define your own type backed by the original 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()