When working with existing types in Go, the need may arise to extend them with custom methods to enhance functionality. However, as the provided sample code indicates, directly adding methods to non-local types is prohibited.
To overcome this limitation, there are primarily two approaches to consider:
1. Defining a Wrapper Type:
Example:
type MyRouter struct { mux.Router // Anonymous field } func (m *MyRouter) F() { ... } r := &MyRouter{origRouter} r.F()
2. Embedding the Original Type:
Example:
type MyRouter struct { *mux.Router // Embedded field } func (m *MyRouter) F() { ... } router := &MyRouter{origRouter} router.F()
Both approaches allow you to extend existing types without modifying the original package. By creating a new type or embedding the original one, you can define additional methods that can operate on instances of your customized type.
The above is the detailed content of How Can I Add Custom Methods to Existing Types in Go?. For more information, please follow other related articles on the PHP Chinese website!