Junior — Middle
Is it possible to extend the functionality of another package in Go by adding new methods?
sobes.tech AI
Answer from AI
In the Go language, you cannot add new methods to types defined in another package if those types are not declared in your package. Methods can only be declared for types defined in the same package. This restriction is related to the language's design and helps prevent conflicts and unpredictable behavior.
However, you can use composition or create new wrapper types that include a type from another package and add their own methods:
package mypkg
import "otherpkg"
type MyType struct {
otherpkg.ExternalType
}
func (m MyType) NewMethod() {
// additional functionality
}
Thus, extending functionality is possible through wrappers, but not by directly adding methods to types from another package.