What is the difference between the general method and the interface method in Go?
There are some differences in the definition and usage of general methods and interface methods in the Go language.
- Different ways of defining:
- Typically, methods are declared directly in the definition of a struct or type using the func keyword.
- Interface method: declare methods in the interface definition without the need to use the func keyword for definition.
- Different ways of implementation.
- Conventional method: call a method through an instance of a struct or type.
- Interface methods: methods are called by implementing the interface’s structure or by creating an instance of the type.
- Different ways of calling:
- Regular method: You can directly invoke the method without the need to call it through an interface.
- Interface methods: methods are called through interface types, meaning they are called through interface variables.
- Various levels of scalability:
- Traditional approach: the definition and implementation of a method are tightly coupled, requiring modifications to the original structure or type definition when expanding methods.
- Interface methods: the definition and implementation are separated, allowing for the extension of methods by implementing other structures or types that share the same interface, without the need to modify the original interface definition.
In general, the usual method is to target specific structures or types, while interface methods target interfaces. Interface methods can offer better scalability and flexibility.