In Go, extending existing types from different packages is not directly supported. However, there are alternative techniques to achieve similar functionality.
One approach is to define a new type that embeds the existing type as an anonymous field. This allows you to define additional methods on your new type without modifying the original. Here's an example:
type MyRoute struct { mux.Route } func (r *MyRoute) Subroute(tpl string, h http.Handler) *mux.Route { return r.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h) }
Another option is to directly embed the existing type as a named field and use the pointers to access and extend the embedded type.
type MyRouter struct { *mux.Router } func (r *MyRouter) Subroute(tpl string, h http.Handler) *mux.Route { return r.Router.PathPrefix("/" + tpl).Subrouter().PathPrefix("/").Handler(h) }
In some cases, it may be feasible to create an extension package that provides additional functionality to existing types. However, this requires modifying the source code of the original package and is generally not recommended for shared libraries.
The appropriate approach depends on the specific requirements and limitations of your project. If you need to access and modify the existing type directly, embedding may be suitable. Consider using anonymous fields if you want to hide the underlying type from the API. Explore extension packages if you have the freedom to modify the original source code.
The above is the detailed content of How Can I Extend Existing Types in Go Without Modifying the Original Code?. For more information, please follow other related articles on the PHP Chinese website!