Advanced Interface Techniques
Type Assertions and Reflection
Type Assertion
func processValue(i interface{}) {
switch v := i.(type) {
case int:
fmt.Println("Integer:", v)
case string:
fmt.Println("String:", v)
default:
fmt.Println("Unknown type")
}
}
Interface Composition
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
type ReadWriter interface {
Reader
Writer
}
Empty Interface Techniques
Technique |
Description |
Use Case |
Type Switching |
Determine runtime type |
Dynamic type handling |
Reflection |
Inspect type metadata |
Advanced type manipulation |
Generic Storage |
Store any type |
Flexible data structures |
Generics and Interfaces
type Comparable[T any] interface {
Compare(other T) int
}
func FindMax[T Comparable[T]](slice []T) T {
if len(slice) == 0 {
panic("empty slice")
}
max := slice[0]
for _, item := range slice[1:] {
if item.Compare(max) > 0 {
max = item
}
}
return max
}
Interface Flow Control
graph TD
A[Interface Method Call] --> B{Type Check}
B --> |Type Matches| C[Execute Method]
B --> |Type Mismatch| D[Handle Error]
Context-Based Interfaces
type Cancellable interface {
Cancel(ctx context.Context) error
}
type Timeoutable interface {
WithTimeout(duration time.Duration) context.Context
}
Interface Method Caching
type CachedOperation interface {
Compute() int
GetCachedResult() int
}
Advanced Error Handling
type CustomError interface {
Error() string
Code() int
Wrap(err error) CustomError
}
Dependency Injection Patterns
type DatabaseRepository interface {
Connect() error
Disconnect() error
Query(sql string) ([]interface{}, error)
}
func NewService(repo DatabaseRepository) *Service {
return &Service{repository: repo}
}
Interface Design Principles
- Minimize interface size
- Design for consumption
- Prefer composition over inheritance
- Use interfaces for abstraction
By mastering these advanced techniques, developers can create more flexible and powerful Go applications. LabEx encourages continuous learning and practice in interface design.