0PricingLogin
Go Academy · Lesson

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

  1. Defining and Implementing Interfaces
  2. Core Standard Library Interfaces
  3. Type Assertions and Type Switches
  4. Interface Composition and Best Practices
← Back to Go Academy