Overview
In Go, an interface is a type that defines a set of method signatures. A type is considered to satisfy an interface when it implements all of the methods declared by that interface.Interfaces allow you to write more flexible code by enabling functions to work with any type that implements the required methods. A type can implement multiple interfaces, and a single interface can be satisfied by multiple types.
Define
shape interface defines two method signatures, area() and perimeter(). Any type that implements these methods is considered a shape.
Implement
Both
circle and rect satisfy the shape interface because they implement all the required methods. This happens automatically, and no explicit declaration is needed.Use
Empty Interface
An empty interface (interface{}) requires zero methods, so every type satisfies it. You can also use the alias any instead of interface{}.
Type Switches
You can use empty interfaces with type switches to handle values of different types at runtime:Type Assertion
Thex.(T) syntax is known as a type assertion. It can be used with any type, including named types and pointer types:
ok variable is true if the type assertion succeeds and false if it fails. When ok is false, val contains the zero value of the asserted type.
Example with Custom Interfaces
Here is an example showing usage with the
shape interface defined above:Interface Composition
Interface composition allows you to create new interfaces by combining existing ones.The
ReadWriter interface requires both Read and Write methods. Any type that implements both methods automatically satisfies the ReadWriter interface.