
Interfaces in GoLang
Interfaces in GoLang
An interface in Go defines a set of method signatures, but it does not provide the implementation. Any type that implements these methods is said to implement the interface. This provides Go with a form of polymorphism, enabling different types to be used interchangeably if they implement the same interface.
Go interfaces are implicit, meaning a type does not have to explicitly declare that it implements an interface. If the type has all the methods the interface defines, it is considered to implement that interface.
Key Features of Interfaces in Go
- No explicit declaration: A type implicitly satisfies an interface by implementing its methods, without needing to explicitly declare it.
- Dynamic polymorphism: Interfaces allow Go to achieve polymorphism, where the same interface can be used for multiple different types.
- Empty interface: The empty interface
interface{}
can hold values of any type.
Declaring and Using Interfaces
To define an interface, you simply list the method signatures that the types must implement.
Example 1: Defining an Interface
import "fmt"func printAnything(value interface{}) { fmt.Println(value)}func main() { printAnything(package main
import "fmt"func main() { package main
import "fmt"// Define a Speaker interfacetype Speaker interface { Speak() string}// Define a struct called Persontype Person struct { Name string}// Implement Speak method for Personfunc (p Person) Speak() type Dog struct { Breed string}// Implement Speak method for Dogfunc (d Dog) Speak() func introduce(speaker Speaker) { fmt.Println(speaker.Speak())}func main() { person := Person{Name: "Alice"} dog := Dog{Breed: "Labrador"} introduce(person) // Output: Hello, my name is Alice introduce(dog) // Output: Woof! I am a Labrador}
Explanation:
- Both
Person
andDog
types implement theSpeak
method, which is defined in theSpeaker
interface. - The
introduce
function accepts aSpeaker
interface, allowing us to pass any type that implementsSpeak
, demonstrating polymorphism.
Summary of Go Interfaces
- Interface declaration: Define an interface by listing the method signatures that types should implement.
- Implicit implementation: A type automatically satisfies an interface if it implements the methods defined in the interface.
- Empty interface:
interface{}
can hold values of any type. - Type assertion: Used to extract the value of a specific type from an interface.
- Polymorphism: Interfaces enable polymorphism in Go, allowing different types to implement the same set of methods and be used interchangeably.
Interfaces are a powerful feature of Go that help create flexible and reusable code, especially when designing systems where different types need to work together.