Core Standard Library Interfaces
fmt.Stringer, io.Reader, io.Writer
fmt.Stringer
fmt.Stringer has one method: String() string. Implement it to control how your type appears with fmt.Println and %v:
package main
import "fmt"
type Color int
const (Red Color = iota; Green; Blue)
func (c Color) String() string {
return []string{"Red","Green","Blue"}[c]
}
func main() {
fmt.Println(Red, Green, Blue) // Red Green Blue
}error Interface
The built-in error interface has one method: Error() string. Any type implementing it can be used as an error:
package main
import "fmt"
type ValidationError struct{ Field, Msg string }
func (e *ValidationError) Error() string {
return e.Field + ": " + e.Msg
}
func validate(age int) error {
if age < 0 { return &ValidationError{"age", "must be non-negative"} }
return nil
}
func main() {
fmt.Println(validate(-1))
}All lessons in this course
- Defining and Implementing Interfaces
- Core Standard Library Interfaces
- Type Assertions and Type Switches
- Interface Composition and Best Practices