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.
Interface definition in 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.
type Speaker interface {
Speak() string
}type Reader interface { Read(p []byte) (n int, err error) }
type Logger interface {
Log(message string)
Error(err error)
}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.
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) }
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.
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.