0
0
Goprogramming~5 mins

Interface use cases in Go

Choose your learning style9 modes available
Introduction

Interfaces let us write flexible code that works with different types. They help us organize and reuse code easily.

When you want different types to share common behavior without sharing code.
When you want to write functions that can accept many different types.
When you want to hide details and only expose what is needed.
When you want to make your code easier to test by using mock implementations.
When you want to design plugins or modules that can be swapped easily.
Syntax
Go
type InterfaceName interface {
    MethodName(params) returnType
}

An interface lists method signatures without implementations.

Any type that has those methods automatically implements the interface.

Examples
This interface requires a Speak method that returns a string.
Go
type Speaker interface {
    Speak() string
}
This interface matches types that can read bytes into a slice.
Go
type Reader interface {
    Read(p []byte) (n int, err error)
}
This interface requires a Log method that takes a message string.
Go
type Logger interface {
    Log(message string)
}
Sample Program

This program shows two types, Person and Robot, both implementing the Greeter interface by having a Greet method. The sayHello function accepts any Greeter and calls Greet. This lets us use different types interchangeably.

Go
package main

import "fmt"

// Define an interface
 type Greeter interface {
    Greet() string
}

// Define a type that implements Greeter
 type Person struct {
    name string
}

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

// Define another type that implements Greeter
 type Robot struct {
    id int
}

func (r Robot) Greet() string {
    return fmt.Sprintf("Beep boop, I am robot #%d", r.id)
}

// Function that accepts any Greeter
 func sayHello(g Greeter) {
    fmt.Println(g.Greet())
}

func main() {
    p := Person{name: "Alice"}
    r := Robot{id: 42}

    sayHello(p) // Person greets
    sayHello(r) // Robot greets
}
OutputSuccess
Important Notes

Interfaces are satisfied implicitly in Go; you don't need to declare it explicitly.

Use interfaces to write flexible and testable code.

Empty interface interface{} can hold any type but should be used carefully.

Summary

Interfaces define behavior by listing method signatures.

Any type with those methods implements the interface automatically.

Interfaces let you write flexible, reusable, and testable code.