0
0
Goprogramming~5 mins

Interface definition in Go

Choose your learning style9 modes available
Introduction

An interface in Go lets you define a set of actions (methods) that a type can do. It helps different types work together if they share these actions.

When you want different types to share common behavior without being the same type.
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 fake versions of types.
When you want to design flexible programs that can grow or change easily.
Syntax
Go
type InterfaceName interface {
    MethodName1(param1 Type1, param2 Type2) ReturnType
    MethodName2() ReturnType
}

Interfaces list method signatures without any code inside.

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 that takes a byte slice and returns a number and an error.
Go
type Reader interface {
    Read(p []byte) (n int, err error)
}
This interface requires two methods: Log and Error, each with different parameters.
Go
type Logger interface {
    Log(message string)
    Error(err error)
}
Sample Program

This program defines a Greeter interface with one method Greet. The Person type has a Greet method, so it implements Greeter. The sayHello function accepts any Greeter and calls Greet. In main, we create a Person and pass it to sayHello, which prints a greeting.

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
}

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

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

In Go, you don't need to explicitly say a type implements an interface; it happens automatically if methods match.

Interfaces help write flexible and testable code by focusing on behavior, not concrete types.

Summary

Interfaces define a set of methods without implementation.

Any type with those methods implements the interface automatically.

Interfaces let you write flexible code that works with many types.