Code Demo
PackageMainImport("FMT" "Math")typeGeometryInterface{Area ()float64Perim ()float64}typeRectstruct{width, heighfloat64}typeCirclestruct{radiusfloat64}func(R Rect) area ()float64{returnR.width * R.heigh}func(R rect) Perim ()float64{return 2*r.width +2*r.heigh}func(c circle) area ()float64{returnMath. Pi * C.radius * C.radius}func(c circle) Perim ()float64{return 2* Math. Pi * C.radius}funcMeasure (g geometry) {fmt. Println (g) fmt. Println (G.area ()) fmt. Println (G.perim ())}funcMain () {r: = rect{width:3, Heigh:4} c: = Circle{radius:5} measure (r) measure (c)}
Code Run Results
{3 4}
12
14
{5}
78.53981633974483
31.41592653589793
Code interpretation:
- An interface is a collection of method signatures, which is the declaration of a method, and to implement an interface, all the methods in the interface must be implemented.
- In the example above, we are going to implement an interface that consists of two methods, namely area and perimeter calculation.
- Above, we want to use the rectangle and the circle, realizes this interface, therefore we must realize the rectangle and the circle area and the circumference computation method finally
- Define the structure of rectangles and circles first
- Then, the area and perimeter calculation method of rectangle is realized, and the area and perimeter of circle are calculated.
- Finally, we instantiate the rectangle and the circle structure, giving the specific value
- In this way, we implement all the methods within the interface. In the future we can use the function measure to receive this interface, you can use the rectangle as a parameter to the interface, to get the area and perimeter of the rectangle, the same can get the area and perimeter of the circle
Interfaces in the 020_go language