Interfaces in the 020_go language

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.