54. Toad Notes Go language--interface use 1

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

The toad notes Go language--interface use 1

It is more difficult to use interface in the Go language. It's easy to use, but it's more difficult to design your own interface. So it is necessary to use interface efficiently.

What is interface

A interface consists of two things: a set of methods (also types), or types.

For example, a animal type can be an interface. Animal can be defined as anything that can be spoken.

Type Animal Interface {

Speak () string

}

This defines the animal, which can be any type that contains the Speak method.

Speak does not have any arguments, and returns a string. Any type that defines the method satisfies the animal interface.

This is automatically implemented without the keyword to specify whether the type satisfies the interface. Create a pair of types to satisfy this interface.

Type Dog struct {

}

Func (d Dog) Speak () string {

Return "woof!"

}

Type Cat struct {

}

Func (c Cat) Speak () string {

Return "meow!"

}

Type Llama struct {

}

Func (L Llama) Speak () string {

return "?????"

}

Type Javaprogrammer struct {

}

Func (J Javaprogrammer) Speak () string {

Return "Design patterns!"

}

There are 4 types of animals: a dog, a cat, a llama, and a Java programmer.

The main functions are as follows:

Func Main () {

Animals: =[]animal{dog{}, cat{}, llama{}, javaprogrammer{}}

For _, animal:= range Animals {

Fmt. PRINTLN (animal. Speak ())

}

}

Run as follows:

woof!

meow!

?????

Design patterns!

interface{} type

The interface{} type is an empty interface. The root of many doubts.

There is no method for an empty interface. Because there is no implemets keyword, the type of at least 0 methods automatically satisfies the null interface. PS: is at least 0, hehe, is any time has been set up oh.

means that if you write a function that takes interface{} as an interface, then this function can accept any value

The following functions:

Func dosomething (v interface{}) {

// ...

}

Accept any parameters.

So the question is, what type is V in the function body? Is it any type? This is not true, V is not of any type, but interface{} type. Any value has a deterministic type at run time, and V is the interface{} type.

In fact, a interface{} value stores 2 data bytes. One for the method table that points to the type, and the other to the data that the value actually holds. If you understand that the interface value is 2 bytes with a pointer to the data, many traps are avoided. For the implementation of the interface interface, you can refer to the following links.

In the previous example, building the animal type of slice, you do not need to use animal (dog{}) to describe the Dog type, in animal slice, each element is a animal type, but different values have different types.

It's really confusing to know how interface is stored in memory. For example, can []t be converted to []interface{}?

It's easy to understand how interface is stored.

Code

Package Main

Import (

"FMT"

)

Func printall (Vals []interface{}) {

For _, Val: =range vals {

Fmt. Println (Val)

}

}

Func Main () {

Names: =[]string{"Stanley", "David", "Oscar"}

Printall (names)

}

The operation error is as follows:

Cannot usenames (type []string) as type []interface {} in argument to Printall

You cannot convert []string to []interface].

If you want to work, you need to convert []string to []interface{}

As follows:

Package Main

Import (

"FMT"

)

func printall (vals[]interface{}) {

for_,val:=rangevals{

FMT. Println (val)

    }

}

func Main () {

names:=[]string{"Stanley","David","Oscar"}

vals:=make ([]interface{},len(names))

fori,v:=rangenames{

vals[i]=v

    }

printall (vals)

}

EXECUTE as follows:

Stanley

David

Oscar

This is really not perfect, but actually []interface{} is rarely used.

Pointers and interfaces

The details of the other interface are the interface definitions. The definition does not describe whether to implement the interface using pointer acceptance or value acceptance. When given an interface value, there is no guarantee that the type is a pointer. In the previous example, the definition of all methods is the value received, assigned to Animal's sclie. Let's change the cat's Speak () method to receive the pointer as follows:

Func (c *cat) Speak () string {

Return "meow!"

}

If allowed, the error will be as follows:

Cannot use Cat literal (typecat) as type Animal in array or slice literal:

Cat does not Implementanimal (Speak method have pointer receiver)

You can override the cat value by pointing the *cat pointer to the animal slice. Also use new (Cat) instead of cat{}

Such as:

Animals: = []animal{dog{}, New (Cat), llama{},javaprogrammer{}}

OK, go ahead.

Pass the *dog pointer instead of the dog value, but do not change the speak function of the dog.

As follows:

Animals: = []animal{new (Dog), New (Cat), llama{},javaprogrammer{}}

can also work correctly. However, the difference is that you do not need to change the receive type of the Speak method. This is because the pointer type can be method-dependent, but the reverse is not possible. *dog can use the Speak method, but a cat cannot access *cat's speak.

The thing to remember is that everything passed in Go is a value. Each time you invoke a function, a copy of the data is passed.

Func (T T) MyMethod (s string) {

// ...

}

The function type is func (t,string), and the function value is passed by value.

The change in the receiver value type defined by the method is not seen by the caller, because the caller is the dog value that sees the complete isolation.

Since everything is passed by value, the obvious *cat method cannot be used by cat values, and any cat value may have any *cat pointers to point to. If you want to invoke a *cat method by using a cat value, you cannot start with the *cat pointer. Conversely, if there is a method based on the dog type, we have a *dog pointer that can be explicitly pointed to a dog value by the *dog pointer, then go runtime associates the pointer to the dog value when needed. So, given a *dog value, and a method of a dog type, you can call the dog method.

Friendship Link

Http://jordanorelli.com/post/32665860244/how-to-use-interfaces-in-go

http://www.laktek.com/2012/02/13/learning-go-interfaces-reflections/

Related Article

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.