Home >Backend Development >Golang >How Can I Add Methods to Existing Types in Go?
Extending Existing Types in Go
When attempting to add custom methods to existing types from imported packages, you may encounter an error indicating that you cannot define new methods on non-local types. This limitation stems from Go's type system, which disallows modifications to types defined elsewhere.
To circumvent this restriction, there are two primary approaches:
type MyRoute struct { *mux.Route } func (m *MyRoute) Subroute(tpl string, h http.Handler) *mux.Route { return m.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h) } type MyRouter struct { *mux.Router } func (r *MyRouter) Subroute(tpl string, h http.Handler) *mux.Route { return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h) }
type MyRoute embed mux.Route func (m *MyRoute) Subroute(tpl string, h http.Handler) *mux.Route { return m.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h) } type MyRouter embed mux.Router func (r *MyRouter) Subroute(tpl string, h http.Handler) *mux.Route { return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h) }
The above is the detailed content of How Can I Add Methods to Existing Types in Go?. For more information, please follow other related articles on the PHP Chinese website!