You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Interfaces are one of Go's most powerful features. Unlike Java or C#, Go interfaces are satisfied implicitly — a type implements an interface simply by having the right methods. There is no implements keyword. This design enables flexible, decoupled code.
An interface specifies a set of method signatures:
type Shape interface {
Area() float64
Perimeter() float64
}
Any type that has Area() float64 and Perimeter() float64 methods automatically satisfies the Shape interface.
type Circle struct {
Radius float64
}
func (c Circle) Area() float64 {
return math.Pi * c.Radius * c.Radius
}
func (c Circle) Perimeter() float64 {
return 2 * math.Pi * c.Radius
}
type Rectangle struct {
Width, Height float64
}
func (r Rectangle) Area() float64 {
return r.Width * r.Height
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Width + r.Height)
}
Both Circle and Rectangle implement Shape implicitly:
func printShape(s Shape) {
fmt.Printf("Area: %.2f, Perimeter: %.2f\n", s.Area(), s.Perimeter())
}
printShape(Circle{Radius: 5})
printShape(Rectangle{Width: 4, Height: 6})
| Feature | Go (Implicit) | Java / C# (Explicit) |
|---|---|---|
| Keyword | None | implements / : IInterface |
| Coupling | Type does not know about the interface | Type must explicitly declare it |
| Third-party types | Can satisfy your interfaces | Cannot — must wrap or modify |
| Compile-time check | At point of use | At point of declaration |
This implicit satisfaction means you can define an interface that existing types already satisfy — without modifying them.
| Interface | Methods | Used For |
|---|---|---|
fmt.Stringer | String() string | Custom string representation |
error | Error() string | Error values |
io.Reader | Read(p []byte) (n int, err error) | Reading data |
io.Writer | Write(p []byte) (n int, err error) | Writing data |
io.Closer | Close() error | Closing resources |
io.ReadWriter | Read + Write | Read and write |
sort.Interface | Len, Less, Swap | Custom sorting |
http.Handler | ServeHTTP(w, r) | HTTP request handling |
json.Marshaler | MarshalJSON() ([]byte, error) | Custom JSON encoding |
json.Unmarshaler | UnmarshalJSON([]byte) error | Custom JSON decoding |
func (u User) String() string {
return fmt.Sprintf("%s (%s)", u.Name, u.Email)
}
fmt.Println(u) // Alice (alice@example.com)
type InfiniteZeros struct{}
func (z InfiniteZeros) Read(p []byte) (int, error) {
for i := range p {
p[i] = 0
}
return len(p), nil
}
interface{} // Go 1.17 and earlier
any // Go 1.18+ (alias for interface{})
The empty interface has no methods, so every type satisfies it:
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.