Data structure and algorithm (golang Implementation) (5) simple introduction to golang interface

Time:2020-7-1

Interface

stayGolangIn the world, there is a kind ofinterfaceIt’s amazing.

1、 Data type interface {}

If you don’t know what data type the variable is, whether it’s an integer or a string, but you still want to use it.

GolangIt’s calledinterface{}Data type, which means that you don’t know what type it is. For example:

package main

import (
    "fmt"
    "reflect"
)

func print(i interface{}) {
    fmt.Println(i)
}

func main() {
    //Declare an unknown type of a, indicating that you do not know what type it is
    var a interface{}
    a = 2
    fmt.Printf("%T,%v\n", a, a)

    //Pass in function
    print(a)
    print(3)
    print("i love you")

    //Use assertions to determine if it is an int data type
    v, ok := a.(int)
    if ok {
        fmt.Printf("a is int type,value is %d\n", v)
    }

    //Use assertions to determine the type of variables
    switch a.(type) {
    case int:
        fmt.Println("a is type int")
    case string:
        fmt.Println("a is type string")
    default:
        fmt.Println("a not type found type")
    }

    //Use reflection to find variable types
    t := reflect.TypeOf(a)
    fmt.Printf("a is type: %s", t.Name())
}

Output:

int,2
2
3
i love you
a is int type,value is 2
a is type int
a is type: int

1.1. Basic use

We useinterface{}Can declare a variable of unknown typea

//Declare an unknown type of a, indicating that you do not know what type it is
    var a interface{}
    a = 2
    fmt.Printf("%T,%v\n", a, a)

Then assign an integer to the variable:a=2At this timeaStill unknown type, use placeholder%TYou can print the real type of a variable, a placeholder%vPrint the valuefmt.PrintfType judgment is performed internally.

We can also set the parameter of the function asinterface, the same as the definition of variables:

func print(i interface{}) {
    fmt.Println(i)
}

When using:

//Pass in function
    print(a)
    print(3)
    print("i love you")

We introducedprintThe arguments to a function can be of any type, such as an integer3Or stringi love youEtc. After entering the function, the variable in the functioniThe missing type is an unknown type, which makes it unnecessary to write multiple functions if we want to process different types of data.

Of course, the fields in the structure can also beinterface{}

type H struct {
    A interface{}
    B interface{}
}

1.2. Determine specific types

We defined itinterface{}But in practice, we need to judge the type. There are two ways to judge.

Use assertion:

//Use assertions to determine if it is an int data type
    v, ok := a.(int)
    if ok {
        fmt.Printf("a is int type,value is %d\n", v)
    }

Use directly after the variable.(int), has two return valuesv, okWill return.okIf it istrueIndicates that it is an integer type, and the integer is assignedvAnd then we can take itvHappy to play. Otherwise,okbyfalsevIs null, which is the default value of 0.

If we use it like this every time, it will be very uncomfortable because oneinterface{}The data type may be.(int)It could be.(string), you can useswitchTo simplify:

//Use assertions to determine the type of variables
    switch a.(type) {
    case int:
        fmt.Println("a is type int")
    case string:
        fmt.Println("a is type string")
    default:
        fmt.Println("a not type found type")
    }

stayswicthAssertion is no longer used(specific type), buta.(type)

Finally, there is another way to use reflection packetsreflectTo determine the data type:

//Use reflection to find variable types
    t := reflect.TypeOf(a)
    fmt.Printf("a is type: %s", t.Name())

This package will directly use unsafe pointers to get the real data type:

func TypeOf(i interface{}) Type {
    eface := *(*emptyInterface)(unsafe.Pointer(&i))
    return toType(eface.typ)
}

Reflection package is rarely used in daily development.

2、 Interface structure

Now we are all functional programming, or structural method programming. Don’t we have the object-oriented and object inheritance features of other languages? yes,GolangLanguage is called interface oriented programming.

package main

import (
    "fmt"
    "reflect"
)

//To define an interface, there is a method
type A interface {
    Println()
}

//To define an interface, there are two methods
type B interface {
    Println()
    Printf() int
}

//Defining a structure
type A1Instance struct {
    Data string
}

//Struct implements the println() method, which is now an a interface
func (a1 *A1Instance) Println() {
    fmt.Println("a1:", a1.Data)
}

//Defining a structure
type A2Instance struct {
    Data string
}

//Struct implements the println() method, which is now an a interface
func (a2 *A2Instance) Println() {
    fmt.Println("a2:", a2.Data)
}

//Struct implements the printf() method, which is now a B interface, which is both a and B interfaces
func (a2 *A2Instance) Printf() int {
    fmt.Println("a2:", a2.Data)
    return 0
}

func main() {
    //Define a variable of type A interface
    var a A

    //The specific structure is assigned to the variable
    a = &A1Instance{Data: "i love you"}
    //Method of calling interface
    a.Println()
    //Assertion type
    if v, ok := a.(*A1Instance); ok {
        fmt.Println(v)
    } else {
        fmt.Println("not a A1")
    }
    fmt.Println(reflect.TypeOf(a).String())

    //The specific structure is assigned to the variable
    a = &A2Instance{Data: "i love you"}
    //Method of calling interface
    a.Println()
    //Assertion type
    if v, ok := a.(*A1Instance); ok {
        fmt.Println(v)
    } else {
        fmt.Println("not a A1")
    }
    fmt.Println(reflect.TypeOf(a).String())

    //Define a variable of type B interface
    var b B
    //B = & a1instance {data: "I love you"} // not of type B
    b = &A2Instance{Data: "i love you"}
    fmt.Println(b.Printf())
}

Output:

a1: i love you
&{i love you}
*main.A1Instance
a2: i love you
not a A1
*main.A2Instance
a2: i love you
0

We can define an interface type using theType interface name interfaceAt this time, it is no longerinterface{}

//To define an interface, there is a method
type A interface {
    Println()
}

//To define an interface, there are two methods
type B interface {
    Println()
    Printf() int
}

You can see the interfaceAandBIs an abstract structure, each interface has some methods in it, as long as the structure bodystructIf these methods are implemented, the structures are all types of this interface. For example:

//Defining a structure
type A1Instance struct {
    Data string
}

//Struct implements the println() method, which is now an a interface
func (a1 *A1Instance) Println() {
    fmt.Println("a1:", a1.Data)
}

//Defining a structure
type A2Instance struct {
    Data string
}

//Struct implements the println() method, which is now an a interface
func (a2 *A2Instance) Println() {
    fmt.Println("a2:", a2.Data)
}

//Struct implements the printf() method, which is now a B interface, which is both a and B interfaces
func (a2 *A2Instance) Printf() int {
    fmt.Println("a2:", a2.Data)
    return 0
}

We require that the struct must implement some methods, so we can define a variable of interface type and assign the struct to it

//Define a variable of type A interface
    var a A
    //The specific structure is assigned to the variable
    a = &A1Instance{Data: "i love you"}
    //Method of calling interface
    a.Println()

If the struct does not implement this method, the compilation fails and the binary cannot be compiled.

You can also use assertions and reflections to determine which actual structure the interface type belongs tostruct

//Assertion type
    if v, ok := a.(*A1Instance); ok {
        fmt.Println(v)
    } else {
        fmt.Println("not a A1")
    }
    fmt.Println(reflect.TypeOf(a).String())

GolangIt is very intelligent to judge whether the structure implements the interface. If so, the structure is the interface type. We can develop more flexible programs by using the characteristics of interface structure and composition.

Entry to series

I’m Chen Xingxing. Welcome to read it myselfData structure and algorithm (golang Implementation), the article started with a more user-friendly gitbook.

  • Data structure and algorithm (implementation of golang) (1) introduction to golang
  • Data structure and algorithm (golang Implementation) (2) a simple introduction to golang packages, variables and functions
  • Data structure and algorithm (golang Implementation) (3) simple introduction to golang process control statements
  • Data structure and algorithm (golang Implementation) (4) simple introduction to golang structure and method
  • Data structure and algorithm (golang Implementation) (5) simple introduction to golang interface
  • Data structure and algorithm (golang Implementation) (6) a simple introduction to golang concurrency, coprogram and channel
  • Data structure and algorithm (golang Implementation) (7) simple introduction to golang standard library
  • Basic knowledge of data structure and algorithm (golang Implementation) (8.1) – Introduction
  • Data structure and algorithm (golang Implementation) (8.2) Basics – divide and conquer and recursion
  • Data structure and algorithm (golang Implementation) (9) basic knowledge algorithm complexity and progressive symbol
  • Data structure and algorithm (golang Implementation) (10) basic knowledge algorithm complexity main method
  • Data structure and algorithm (golang Implementation) (11) common data structure – Preface
  • Data structure and algorithm (golang Implementation) (12) common data structure linked list
  • Data structure and algorithm (golang Implementation) (13) common data structure variable length array
  • Data structures and algorithms (golang Implementation) (14) common data structures stacks and queues
  • Data structures and algorithms (golang Implementation) (15) common data structures – Lists
  • Data structure and algorithm (golang Implementation) (16) common data structure dictionary
  • Data structure and algorithm (golang Implementation) (17) common data structure tree
  • Data structure and algorithm (golang Implementation) (18) sorting algorithm – Preface
  • Data structure and algorithm (golang Implementation) (19) sorting algorithm bubble sort
  • Data structure and algorithm (golang Implementation) (20) sorting algorithm selection sort
  • Data structure and algorithm (golang Implementation) (21) sort algorithm insert sort
  • Data structure and algorithm (golang Implementation) (22) sorting algorithm Hill sort
  • Data structure and algorithm (golang Implementation) (23) sorting algorithm merge sort
  • Data structure and algorithm (golang Implementation) (24) sorting algorithm priority queue and heap sort
  • Data structure and algorithm (golang Implementation) (25) sorting algorithm quick sort
  • Data structure and algorithm (golang Implementation) (26) lookup algorithm hash table
  • Data structure and algorithm (golang Implementation) (27) search algorithm binary search tree
  • Data structure and algorithm (golang Implementation) (28) search algorithm AVL tree
  • Data structure and algorithm (golang Implementation) (29) search algorithm-2-3 tree and left-handed red black tree
  • Data structure and algorithm (golang Implementation) (30) search algorithm-2-3-4 tree and common red black tree

Recommended Today

Swift advanced (XV) extension

The extension in swift is somewhat similar to the category in OC Extension can beenumeration、structural morphology、class、agreementAdd new features□ you can add methods, calculation attributes, subscripts, (convenient) initializers, nested types, protocols, etc What extensions can’t do:□ original functions cannot be overwritten□ you cannot add storage attributes or add attribute observers to existing attributes□ cannot add parent […]