0
0
Goprogramming~5 mins

Why interfaces are used in Go

Choose your learning style9 modes available
Introduction

Interfaces let us write flexible code that works with different types without knowing their exact details.

When you want different types to share common behavior.
When you want to write functions that accept many types.
When you want to change parts of your program easily without rewriting everything.
When you want to test your code by replacing real parts with fake ones.
When you want to design clear contracts for what types should do.
Syntax
Go
type InterfaceName interface {
    MethodName1(params) returnType
    MethodName2(params) returnType
}

Interfaces list method signatures without implementation.

Any type that has these methods automatically implements the interface.

Examples
This interface requires a Speak method that returns a string.
Go
type Speaker interface {
    Speak() string
}
This interface requires a Read method with specific parameters and return values.
Go
type Reader interface {
    Read(p []byte) (n int, err error)
}
Sample Program

This program shows how an interface lets a function accept any type that can greet. Person has a Greet method, so it works with sayHello.

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
}

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

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

Interfaces help separate what something does from how it does it.

In Go, you don't need to declare that a type implements an interface; it happens automatically.

Summary

Interfaces define behavior without details.

They let different types work together easily.

They make code flexible and easier to change.