Some notes about the Go interface

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

What is an interface

Interface is one of the most important features of Golang, and in Go, the interface interface is really no different from the interface meaning of other languages. Interface understands it as a type of specification or convention. Does one type "implement" an interface? It depends on whether this type implements all the methods defined in the interface. the⼝ is a collection of one or more method signatures, and any non-interface type is implemented with all of its corresponding methods (including the same name, parameter list, and return value). ), it means that it "implements" the interface without explicitly adding an interface declaration on that type. This method is also known as Duck Type.

instantiation of an interface

An interface is a type that can be instantiated, not just a constraint specification on a language. When we create an interface variable, it allocates memory for it and copies the object that is assigned to it. The value copy behavior occurs when an object is assigned to an interface variable. Yes, a pointer to this replica is stored inside the interface. And we can't modify the state of this replica, nor can we get its pointers.

Package Mainimport ("FMT") type Painter interface {draw ()}type Xiaowang struct {}func (Xiaowang) Draw () {fmt. Println ("I am drawing a paper.")//Painting}func main () {var xw xiaowangvar painter painter = Xwpainter. Draw () var painter2 Painter = &xwpainter2. Draw () Painter3: = Painter (XW) Painter3. Draw () Painter4: = Painter (&XW) painter4. Draw ()}

In this program, the above instantiation methods are correct, because runtime will help us adjust the * and non-*.

However, if you change the previous recipient of draw to *xiaowang, that is:

Func (*xiaowang) Draw () {fmt. Println ("I am drawing a paper.")//painting}

Then the non-pointer instantiation will be error, the following prompt:

. \main.go:25:cannot use XW (type Xiaowang) as type Painter on Assignment:xiaowang does not implement Painter (Draw method Requires pointer receiver). \main.go:29:cannot convert XW (type Xiaowang) to type Painter:xiaowang does not implement Pai Nter (Draw method requires pointer receiver)

Type-oriented interface

In Golang, type implements a one-to-many, which means that the type keyword can be used to define a variety of different types. Interface supports many-to-one, which means that any type can be received by the interface type.

In the go language, you can use the Type keyword to convert one type to another to keep the nature of the data intact, such as:

Type age inttype Height inttype Grade int
Type is not just a typedef corresponding to C/ It is not used to define a series of aliasesits role is to define a series of mutually unrelated behavioral characteristics: Through these cross-irrelevant behavioral characteristics, essentially the same thing shows the characteristics of different things. Take the above code for example: int or the int,age, Height, grade are all int, but the different types defined by the type as an int are completely irrelevant; age, Height, grade are completely different types (that is, for different objects). We can define the following different behaviors (represented as methods or functions) for age, Height, grade, respectively:
Func (a Age) old () bool {    return a > 50}func (L Length) needticket () bool {    return L > 120}func (g Grade) Pa SS () bool {    return G >= 60}
This distinguishes between various derived types that are based on Int. Let's look at a more complicated example:
Type Painter Interface {    draw ()}type Cowboy Interface {    draw ()}type xiaoming struct {}type xiaomingaspainter Xiao Mingfunc (P *xiaomingaspainter) Draw () {    fmt. Println ("I ' m painting.")} Func Main () {    var xm xiaoming    var painter painter = (*xiaomingaspainter) (&XM)    painter. Draw ()}
The above two interfaces all include the draw () method, if the type of xiaoming is just a painter, then how to implement the painter interface? Here you need to understand a concept: interface is not an isolated existence, it is an abstraction of type. And the same thing/data can have more than one type. Xiao Ming is a person (this is implemented as a struct), the painter is only one of his identity, so the painter's behavior characteristics independent as a type, but also the implementation of painter interface. If you want him to be a painter, just convert xiaoming to the painter's identity (through the statement "var painter painter = (*xiaomingaspainter) (&XM)"). So, Xiaoming will still be mistaken for a cowboy? Obviously there is no such possibility.

So if Xiao Wang is both a painter and a cowboy, let Xiao Wang have both the cowboy and the painter's identity (type) to:

Type Painter Interface {    draw ()}type Cowboy Interface {    draw ()}type xiaowang struct {}type xiaowangaspainter Xiao Wangfunc (P *xiaowangaspainter) Draw () {    fmt. Println ("I ' m painting.")} Type Xiaowangascowboy Xiaowangfunc (P *xiaowangascowboy) Draw () {    fmt. Println ("I ' M Drawing.")} Func Main () {    var xw xiaowang    var painter painter = (*xiaowangaspainter) (&xw)    painter. Draw ()    var cowboy cowboy = (*xiaowangascowboy) (&XW)    Cowboy. Draw ()}

The go implementation distinguishes between different types of behavioral traits and links them from the nature of the data (all a person's different identities), which fully embodies the go language's understanding of objects and data.

The popular point is to define the different types, and then define the corresponding methods according to these types. This allows different types to implement different interfaces, although these types of raw data may be the same. This also embodies the idea of object-oriented programming.

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.