0
0
Goprogramming~5 mins

Implementing interfaces in Go

Choose your learning style9 modes available
Introduction

Interfaces let you define a set of actions that different things can do. This helps you write flexible and reusable code.

When you want different types to share common behavior without sharing code.
When you want to write functions that can work with many types as long as they follow certain rules.
When you want to separate what something does from how it does it.
When you want to make your code easier to test by using mock implementations.
When you want to design your program around capabilities instead of specific types.
Syntax
Go
type InterfaceName interface {
    MethodName1(paramType) returnType
    MethodName2(paramType) returnType
}

// To implement the interface, a type must have all methods with matching signatures

func (t TypeName) MethodName1(paramType) returnType {
    // method body
}

func (t TypeName) MethodName2(paramType) returnType {
    // method body
}

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

Interfaces describe behavior, not data.

Examples
This example shows an interface Speaker with one method Speak. The type Dog implements it by defining Speak.
Go
type Speaker interface {
    Speak() string
}

type Dog struct {}

func (d Dog) Speak() string {
    return "Woof!"
}
This shows an interface with a method that takes and returns values. Any type with this method matches the interface.
Go
type Reader interface {
    Read(p []byte) (n int, err error)
}

// Any type with Read method matching this signature implements Reader interface.
Sample Program

This program defines an interface Greeter with one method Greet. The type Person implements it. The function sayHello accepts any Greeter and calls Greet. In main, we create a Person and pass it to 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, my name is " + p.name
}

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

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

You don't need to write extra code to say a type implements an interface; Go figures it out automatically.

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

Interfaces help you write code that works with many types, making your programs more flexible.

Summary

Interfaces define a set of methods that types can implement.

Types implement interfaces by having all the required methods.

This allows writing flexible and reusable code that works with different types.