You're designing a package in Go that deals with various shapes like circles, squares, and triangles. Which approach would you use to define a common behavior for these shapes?
- Use anonymous functions to encapsulate shape-specific logic.
- Use global variables to store shape information.
- Use interfaces to define a common behavior for the shapes.
- Use structs with embedded fields to inherit common behavior.
In Go, interfaces are a powerful tool for defining common behaviors across different types. By defining an interface with methods such as Area() or Perimeter(), each shape type can implement these methods according to its own logic. This approach allows for flexibility and polymorphism, enabling code to work with any shape that satisfies the interface contract. Using interfaces promotes cleaner code, decouples implementation details, and facilitates testing and extensibility.
Loading...