Interfaces and polymorphism are important concepts in object-oriented programming that are also present in Go. Interfaces allow you to define behavior that can be implemented by different types, enabling polymorphism and code reuse. Let's explore interfaces and polymorphism in Go in detail, along with examples.
Interfaces in Go:
An interface is a type that specifies a set of method signatures. A type that implements all the methods of an interface is said to satisfy that interface.
Defining an Interface:
Interfaces are defined using the 'interface' keyword followed by a set of method signatures.
type Shape interface { Area() float64 Perimeter() float64 }
In this example, the 'Shape'interface has two methods: 'Area()'and 'Perimeter()'.
Implementing an Interface:
A type satisfies an interface if it implements all the methods of that interface.
Polymorphism allows different types to be treated as instances of a common supertype. In Go, this is achieved through interfaces.
Example of Polymorphism:
func main() { circle := Circle{Radius: 5} PrintShapeInfo(circle) }
In this example, the'PrintShapeInfo'function works with different types that satisfy the 'Shape' interface, demonstrating polymorphism.
Empty Interfaces:
An empty interface ( 'interface{}') specifies no methods and can hold values of any type. It's often used for dynamic types or as function parameters that accept different types.
To extract the concrete value from an empty interface, you use type assertion.
value, ok := val.(int) if ok { // value is an int }
Type Switch:
A type switch allows you to inspect the dynamic type of an interface value.
switch val := val.(type) { case int: // val is an int case string: // val is a string }
Summary:
Interfaces define a set of method signatures.
Types implementing all methods of an interface satisfy that interface.
Interfaces enable polymorphism, allowing different types to be treated as instances of a common supertype.
Empty interfaces ( 'interface{}') can hold values of any type.
Type assertion and type switch are used to work with values in empty interfaces.
Understanding interfaces and polymorphism in Go allows you to write flexible and reusable code that can work with different types, enhancing code organization and modularity.