snippetgoCritical
How to add new methods to an existing type in Go?
Viewed 0 times
howexistingmethodsaddtypenew
Problem
I want to add a convenience util method on to
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?
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:
or by embedding the original router:
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()Code Snippets
type MyRouter mux.Router
func (m *MyRouter) F() { ... }type MyRouter struct {
*mux.Router
}
func (m *MyRouter) F() { ... }
...
r := &MyRouter{router}
r.F()Context
Stack Overflow Q#28800672, score: 291
Revisions (0)
No revisions yet.