This is a creation in Article, where the information may have evolved or changed.
What is an interface
An interface is a collection of a set of methods. For example, the Geometry interface contains two methods for area and perimeter, and for any type that implements both methods, it belongs to the geometry.
type Geometry interface { Area() float64 Perim() float64}type Rect struct { Width, Height float64}type Circle struct { Radius float64}func (r Rect) Area() float64 { return r.Width * r.Height}func (r Rect) Perim() float64 { return 2 * (r.Width + r.Height)}func (c Circle) Area() float64 { return math.Pi * c.Radius * c.Radius}func (c Circle) Perim() float64 { return math.Pi * c.Radius * 2}
What do you mean, non-intrusive interface?
First you need to know what an intrusive interface is. In Java, for example, you need to explicitly create a class to implement an interface, which is an intrusive interface.
public interface Geometry { public float Area();}public class Rect implements Geometry { ... @override public float Area(){ .... }}
In the case of Golang, we did not tell react or circle the two structs anywhere in the code that they needed to implement the Geometry interface, but instead directly implemented the two methods in the interface. And when they implement these two methods, they become geometry.
func Measure(g Geometry) { fmt.Println(g) fmt.Println(g.Area()) fmt.Println(g.Perim())}r := Rect{3,5}c := Circle{4}Measure(r)Measure(c)
Benefits of non-intrusive interfaces
The most important benefit is that you don't have to import a package in order to implement an interface. To implement an interface, it is good to implement the method it contains directly.
In addition, you do not need to write the type of the first way to design the interface of the problem, directly to provide the method to write the whole. As to which method is which interface, do not worry too much.