Interfaces in Go
Interfaces
84
In Go, interfaces provide a way to specify behavior that types should have without specifying their implementation. They define a set of methods that a type must have in order to satisfy the interface.
For example, let's say we have an interface Animal
that declares a Speak
method:
type Animal interface { Speak() string }
This interface defines that any type that implements the Speak()
method can be treated as an "Animal". Now any type that has a Speak()
method can be used wherever an Animal
is expected.
For instance, we can create a Dog
struct that has a Speak()
method, and use it as an Animal
:
type Dog struct { name string } func (d Dog) Speak() string { return fmt.Sprintf("%s says: Bark!", d.name) } func main() { var animal Animal animal = Dog{"Fido"} fmt.Println(animal.Speak()) // output: Fido says: Bark! }
In this example, since Dog
has a Speak()
method, it satisfies the Animal
interface and can be used as an Animal
.
Interfaces in Go are useful because they decouple the implementation details of a type from its behavior. This allows for loosely coupled and more maintainable code.
March 27, 2023