0
0
Goprogramming~5 mins

Interface satisfaction in Go

Choose your learning style9 modes available
Introduction

Interfaces let us write flexible code by defining what methods a type must have. Interface satisfaction means a type has all methods an interface needs, so it can be used wherever that interface is expected.

When you want different types to share common behavior without being related by inheritance.
When you want to write functions that can accept many types as long as they have certain methods.
When you want to swap implementations easily without changing the code that uses them.
When you want to test code by using mock types that satisfy interfaces.
When you want to organize code by behavior rather than by concrete types.
Syntax
Go
type InterfaceName interface {
    Method1(params) returnType
    Method2(params) returnType
}

// A type satisfies an interface if it has all methods listed in the interface.
type MyType struct {}

func (m MyType) Method1(params) returnType {
    // implementation
}

func (m MyType) Method2(params) returnType {
    // implementation
}

In Go, you don't explicitly declare that a type implements an interface. It happens automatically if the type has all required methods.

This is called 'implicit interface satisfaction' and helps keep code simple and flexible.

Examples
Here, Dog satisfies the Speaker interface because it has the Speak method.
Go
type Speaker interface {
    Speak() string
}

type Dog struct {}

func (d Dog) Speak() string {
    return "Woof!"
}
File satisfies the Reader interface by implementing the Read method.
Go
type Reader interface {
    Read(p []byte) (n int, err error)
}

type File struct {}

func (f File) Read(p []byte) (int, error) {
    // read data into p
    return 0, nil
}
Sample Program

This program shows a Person type that satisfies the Greeter interface by having a Greet method. The sayHello function accepts any Greeter. We pass a Person to it, and it works because Person satisfies the interface.

Go
package main

import "fmt"

type Greeter interface {
    Greet() string
}

type Person struct {
    name string
}

func (p Person) Greet() string {
    return "Hello, " + p.name
}

func sayHello(g Greeter) {
    fmt.Println(g.Greet())
}

func main() {
    p := Person{name: "Alice"}
    sayHello(p) // Person satisfies Greeter interface
}
OutputSuccess
Important Notes

Interface satisfaction is checked automatically by the Go compiler.

If a type misses even one method from the interface, it does not satisfy it.

You can use interfaces to write more testable and flexible code.

Summary

Interfaces define a set of methods a type must have.

A type satisfies an interface by implementing all its methods.

Go uses implicit interface satisfaction, so no extra declaration is needed.