Go🔧Core Languagebeginner
Interfaces
Go · Core Language · Run with go run
Explanation
Interfaces in Go are satisfied implicitly — a type implements an interface simply by having the required methods, with no `implements` keyword. This enables loose coupling: packages define small interfaces, and any type that happens to match can be used. The most famous Go interface is `io.Reader` with its single `Read([]byte) (int, error)` method.
Real-World Scenario
A logging library accepts an `io.Writer` interface. You can pass `os.Stdout`, a `bytes.Buffer`, a file, a network connection, or your own custom writer — all without modifying the logging library.
Quick Snippet
snippet.go
type Stringer interface {
String() string
}
type Temperature struct {
Celsius float64
}
// Temperature implicitly satisfies Stringer
func (t Temperature) String() string {
return fmt.Sprintf("%.1f°C", t.Celsius)
}
func Print(s Stringer) {
fmt.Println(s.String())
}
Print(Temperature{36.6}) // 36.6°CFull Example
interfaces.go
// Compile: go run interfaces.go
// Output:
// 36.6°C
// -273.1°C
package main
import "fmt"
type Stringer interface {
String() string
}
type Temperature struct {
Celsius float64
}
func (t Temperature) String() string {
return fmt.Sprintf("%.1f°C", t.Celsius)
}
func Print(s Stringer) {
fmt.Println(s.String())
}
func main() {
Print(Temperature{36.6})
Print(Temperature{-273.15})
}
Run command
go run interfaces.go