Default Methods in Go
16 days ago
- #Interfaces
- #Structural Typing
- #Go
- Go interfaces use structural typing, not nominal typing, meaning types implicitly satisfy interfaces if they have the required methods.
- Structural typing in Go leads to implementation issues, such as difficulty documenting interface satisfaction and accidental conformances.
- Type assertions in Go require runtime reflection to check method sets, impacting performance.
- Interfaces cannot be extended without breaking existing implementations due to the lack of default method implementations.
- The `flag.Value` interface in Go's standard library is problematic, with optional methods like `IsBoolFlag` only documented, not enforced.
- Embedding in Go allows types to inherit methods from embedded structs, which can be used to work around interface limitations.
- Unexported methods in interfaces can enforce embedding requirements, ensuring types must embed a specific struct to satisfy the interface.
- Adding new methods to interfaces risks breaking existing code if types already define methods with the same name but different signatures.
- Proposals for improving interfaces include optional methods and related interface optimizations, but these face technical challenges.
- Go's interface design, while simple, creates long-term maintenance and extensibility issues.