Go Language Learning-interface

Source: Internet
Author: User

While the go language does not have the concept of class and integration in the traditional object-oriented language, it provides support for interfaces that can use some object-oriented features.

In the Go language, the interface has the following features:

    • A signature that can contain 0 or more methods
    • Defines only the signature of the method and does not contain the implementation
    • Implementing an interface does not require explicit declaration, just implement the appropriate method to
Definition of the interface

This is defined in the following way:

typeinterface {    method1(param_list) return_list    method2(param_list) return_list    ...}

The namer here is the name of the interface, as long as it conforms to the rules of the identifier. However, the name of the normally agreed interface is best to end with ER, R, able (as the case may be), so that it is known as an interface at a glance.

Implementing interfaces

Implementation of the interface in Go is very simple, do not need to explicitly declare the implementation of an interface, want to implement an interface, only need to implement all the methods in the interface.

 PackageMainImport "FMT"Import "Math"typeShaperInterface{Area ()float32Circumference ()float32}typeRectstruct{Widthfloat32Heightfloat32}typeCirclestruct{Radiusfloat32}func(R Rect) Area ()int{returnR.width * R.height}func(R Rect) Circumference ()int{return 2* (R.width + r.height)}func(c Circle) Area ()int{returnMath. Pi * C.radius * C.radius}func(c Circle) Circumference ()int{returnMath. Pi *2* C.radius}funcMain () {r: = rect{Ten, -} FMT. Printf ("Rect w:%f, D:%f, area:%f, circumference:%f", R.width, R.height, R.area (), R.circumference ()) c: = circle{5} FMT. Printf ("Circle r:%f, Area:%f, circumference:%f", C.radius, C.area (), C.circumference ())}

Above we define a Shaper interface, which contains two methods area and circumference, which are used to calculate areas and perimeters respectively. We then defined two struct Rect, Circle and implemented the two methods separately. But the above program doesn't seem to reflect the relationship between the interface and the two implementation types, and we'll use them in the following context:

func showInfo(s Shaper) {    fmt.Printf("Area: %f, Circumference: %f", s.Area(), s.Circumference())}

Note that the parameter of the method here is an interface type, so we can pass an instance of the type that implements the interface, like this:

r := Rect{10, 20}showInfo(r)c := Circle{5}showInfo(c)
Get the actual type that implements the interface

In the above showinfo we pass in an object of the interface type, and if we pass the type that implements the interface, then the other features of the actual type will be masked, so usually we want to get its true type, and we can use the following method:

func showInfo(s Shaper) {    switch s.(type) {    case Rect:        fmt.Println("This is Rect")    case Circle:        fmt.Println("This is Circle")            }    fmt.Printf("Area: %f, Circumference: %f\n", s.Area(), s.Circumference())}

You can also use type assertions to determine whether an interface is a specific type at a given moment.

v, ok := s.(Rect)   // s 是一个接口类型

If S is actually a rect type, then S is converted to the Rect type, and OK is true. Otherwise OK is false.

Common interface Io in the standard library. Reader and IO. Writer

These two interfaces define the basic operation of implementing the IO function, so that a type can perform IO operations as long as the two interfaces are implemented.

The Reader interface is defined as:

typeinterface {    Read(p []byteinterror)}

Just this method, the Read method reads Len (p) bytes of data from the data stream into the byte array p, and returns the number of bytes read (even if an error occurs, N returns the number of bytes that have been read).

We may often use the object that implements the Reader interface: OS. Stdin (Standard input), OS. An instance of file, and so on, we can call the Read method to read the data.

Definition of Writer interface:

typeinterface {    Write(p []byteinterror) }

Write writes Len (p) bytes of data from p to the basic data stream. The number of bytes written n (0 <= n <= len (p)) and any errors encountered that caused the write to stop prematurely.

Similar objects that implement the Writer interface are: OS. Stdout, OS. Stderr, OS. File, and so on. You can write data to it using the Write method.

There are a lot of interfaces defined in the standard library, just a simple mention, and much more to see the documentation for the standard library.

Go Language Learning-interface

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.