Sort of go fragments Interface Language

interface

Interface (interface) defines an object code of conduct, not only define specifications implemented, be implemented by the concrete object specification details.

Interface Type

However, in Go Interface (interface) is one type is an abstract type.
interface is a set of method, is a duck-type programming reflected. Interface do things like define a protocol (rule), so long as a machine with laundry and drying functions, I would call it a washing machine. Do not care about the properties (data), only care about the behavior (methods).
Go language in order to protect your career, keep in mind Interface (interface) is a type.

Why use an interface

package main
import (
    "fmt"
)
type Cat struct{}
func (c Cat)Say() string{
    return "喵喵喵"
}
type Dog struct{}
func (d Dog)Say() string{
    return "汪汪汪"
}
func main(){
    c := Cat{}
    fmt.Println("猫:",c.Say())
    d := Dog{}
    fmt.Println("狗:",d.Say())
}

The above code defines cats and dogs, and then they will call, you will find that the main function of the obvious duplication of code, if pigs, frogs and other animals on our follow along with it, our code will be repeated down. Then we can use them as "can call the animal" to deal with it?
Similar examples will often encounter in the course of our programming:
for example, an online shopping mall may use Paypal, micro-letters, UnionPay online payment way to go, we can not use them as "payment" to deal with it?
Such as triangle, square, circle can calculate perimeter and area, we can not put them all as "Graphics" to deal with it?
Such as sales, administrative, programmers can calculate the monthly salary, we can not put them all as "employees" to deal with it?
Go language in order to solve problems similar to the above, on the design of the interface concept. Before the interface is different from all of the specific type, an interface is an abstract type us, when you see the value of an interface type, you do not know what it is, it is the only one who knows what to do by its methods.

Defined interfaces

Go language advocate oriented programming interface.
Each interface consists of a number of methods composition, format of the interface is defined as follows:

type 接口类型名 interface {
    方法名1(参数列表1) 返回值列表1
    方法名2(参数列表2) 返回值列表2
    ...
}

among them:

  • Interface name: Use the type interface is defined as a custom type name. Go language interface in naming, usually added at the end of a word er, if a write operation interface called the writer, there is a string function interface called Stringer and so on. The best type of interface name to highlight the meaning of the interface.
  • Method name: When the method name and the first letter is capitalized the first letter of the name of this type of interface is capitalized upon, this method can be accessed outside of the code package (package) is where the interface.
  • Parameter list, return the list: the parameter list and return to the parameter variable name in the list of values ​​can be omitted.

for example:

type writer interface{
    Write([]byte) err
}

When you see the value of this interface type, you do not know what it is, but the only thing you know is that you can do something through its Write method.

Implementation of the interface conditions

An object as long as the interface to achieve all of the methods defined inside, then he is the reality of this interface. We define a Animal Interface:

type Sayer interface{
    say()
}

Dog and cat define two structures

type dog struct{}

type cat struct{}

Sayer interfaces because there is only one method say, so we just give the dog and cat were achieved say the method can be achieved Sayer interfaces up.

//dog实现了Sayer接口
func (d dog) say(){
    fmt.Println("汪汪汪")
}
//cat实现了Sayer接口
func (c cat) say(){
    fmt.Println("喵喵喵")
}

Implementation of the interface is so simple, as long as the realization of all the methods in the interface, it implements this interface.

Interface type variable

It implements the interface of what use is it?
Interface type variable capable of storing all instances implements the interface, such as the example above, the type of variable capable of storing Sayer dog and cat types of variables.

func main(){
    var x Sayer
    a := cat{}
    b := dog{}
    x =a 
    x.say()
    x = b
    x.say()
}

Recipients and the pointer value difference between the receiver implements the interface

Implement the interface using the value of the recipient and the recipient implements the interface pointers What difference does it make? Next we look at an example by the difference.
We have a Mover interface and a dog structures.

type Mover interface{
    move()
}
type dog struct{}

Value receiver implements the interface

func (d dog)move(){
    fmt.Println("狗会动")
}

Implementation of the interface at this time is dog type:

func main(){
    var x Mover
    var wangcai = dog{}
    x = wangcai
    var fugui = &dog{}
    x = fugui
    x.move()
}

We can see from the above code, after which the value of the receiver used to implement an interface structure whether or dog structure pointer dog types of variables can be assigned to the interface variables. Because the Go language has evaluated syntactic sugar for pointer type variable, pointer dog inside fugui automatically evaluated fuzhi.

Pointer receiver implements the interface

The same code we come to test the use of pointers recipient What is the difference:

func(d *dog)move(){
    fmt.Println("狗会动")
}
func main(){
    var x Mover
    var wangcai = dog{}
    x = wangcai
    var fugui = &dog{}
    x = fugui
}

At this realization Mover interface is * dog type, it is not the type of dog to incoming x wangcai, this time can only store values ​​of x ** dog type.

Relationship with the interface

A type can implement multiple interfaces simultaneously, and between interfaces independent of each other, do not know each other's implementation. For example, a dog can be called, you can move, we can define Sayer Mover interfaces and interfaces, as follows: Mover interface.

type Sayer interface{
    say()
}
type Mover interface{
    move()
}

Sayer dog can achieve both interfaces can also be achieved Mover interface.

type Sayer interface{
    say()
}
type Mover interface{
    move()
}
type dog struct{
    name string
}
func (d dog)say(){
    fmt.Printf("%s会叫汪汪汪\n",d.name)
}
func (d dog)move(){
    fmt.Printf("%s会动\n",d.name)
}
func main(){
    var x Sayer
    var y Mover
    var a = dog{
        name:"旺财"
    }
    x = a
    y = a
    x.say()
    y.move()
}

Multiple types implement the same interface
GO languages of different types can also implement the same interface, we first define a Mover interface, which consists of a method must move.

type dog struct{
    name string
}
type car struct{
    brand string
}
func (d dog)move(){
    fmt.Printf("%s会跑\n",d.name)

}
func (c car)move(){
    fmt.Printf("%s速度70迈\n",c.brand)
}
func main(){
    var x Mover
    var a = dog{name:"旺财"}
    var b = car{brand:"宝马"}
    x = a
    x.move()
    x = b
    x.move()
}

Ah execution result with the above as follows:

旺财会跑
宝马速度70迈

And an interface method is not necessarily required to achieve a fully type, interface method may be implemented by embedding the other type or types of structures.

type washingmachine interface{
    wash()
    dry()
}
type dryer struct{}
func (d dryer) dry(){
    fmt.Println("甩一甩")
}
type haier struct{
    dryer
}
func (h haier)wash(){
    fmt.Println("洗刷刷")
}

Nesting Interface

The interface between the interface and can create a new interface by nesting.

type Sayer interface{
    say()
}
type Mover interface{
    move()
}
type animal interface{
    Sayer
    Mover
}

Use interface and common interface nested get, like, here we let the cat to achieve animal Interface:

type Sayer interface{
    say()
}
type Mover interface{
    move()
}
type animal interface{
    Sayer
    Mover
}
type cat struct {
    name string
}
func (c cat)say(){
    fmt.println("喵喵喵")
}
func (c cat)move(){
    fmt.Println("猫会动")
}
func main(){
    var x animal
    x = cat{name:"花花"}
    x.move()
    x.say()
}

Air Interface

Define the empty interface

Empty interface type variable can store any type of variable.

func main(){
    var x interface{}
    s := "hello 沙河"
    x = s
    fmt.Printf("type:%T value:%v\n",x,x)
    i :=100
    x = i
    fmt.Printf("type:%T value:%v\n", x,x)
    b := true
    x = b
    fmt.Printf("type:%T value:%v\n", x,x )
}

Application of empty interface

Empty interface as a parameter
empty interface may receive any type of function parameters.

func show(a interface{}){
    fmt.Printf("type:%T value:%v\n", a,a)
}

Empty interface as a value map is
an empty interface can save any value of the dictionary.

var studentInfo = make(map[string]interface{})
studentInfo["name"] = "沙河娜扎"
studentInfo["age"] = 18
studentInfo["married"] = false
fmt.Println(studentInfo)

Type assertion

Empty interface can store any type of value, then how do we get specific data stored in it?

Interface value

Value (the value of the interface) is an interface by the "one particular type" and "value specific type of" two-part. These two parts are referred to as "dynamic type" and "dynamic values" interface.
Let's look at a concrete example:

var w io.Writer
w = os.Stdout
w = new(bytes.Buffer)
w = nil

Want to determine the value of the empty interface this time we can use the type of assertion, its syntax is:

x.(T)

Wherein:
X represents a variable of type interface {}.
T x represents the assertion might be the type.
The syntax returns two parameters, the first parameter is a variable x to the T type, the second value is a Boolean value, if true, it said assertion successful, if the assertion is false indicates failure.
for example:

func main(){
    var x interface{}
    x = "hello 沙河"
    v,ok := x.(string)
    if ok {
        fmt.Println(v)
    }else {
        fmt.Println("类型断言失败")
    }
}

The example above, if desired assertion many times you need to write more if the judge, this time we can use a switch statement to achieve:

func justifyType(x interface{}){
    switch v := x.(type){
    case string:
        fmt.Printf("x is a string; value is %v\n",v)
    case int:
        fmt.Printf("x is a int,value is %v\n",v)
    case bool:
        fmt.Printf("x is a bool, value is %v\n",v)
    default:
        fmt.Printf("unsupport type!")
    }
}

Because empty interface can store any type of value characteristics, so the use of air interface Go language is widely used.
Note that on the interface only when there are two or more than two particular types must be treated in the same manner to define interfaces. Do not write to the interface and the interface. It would only add unnecessary abstraction, resulting in unnecessary loss of run time.

Guess you like

Origin blog.51cto.com/13766835/2414027