Go's non-intrusive interface

Source: Internet
Author: User
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.

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.