当前位置:网站首页>go interface

go interface

2022-04-23 20:43:00 baboon_ chen

One 、 Definition of interface

  An interface is a collection of one or more method signatures , As long as any type has all the methods corresponding to this , It means it's Realization The interface .

  • Pick up ⼝ Naming habits with er ending , Structure .
  • Pick up ⼝ Only method signature , It didn't come true .
  • Pick up ⼝ No data fields .
  • But you can pick up ⼝ Inlay ⼊ Other connections
  • Type can implement multiple connections ⼝.

Two 、 Empty interface

  Air connection ⼝ interface{} There is no ⽅ Legal signature , This means that any type implements null connection ⼝. therefore , An empty interface can store any type of data .

3、 ... and 、 The execution mechanism of the interface

  Pick up ⼝ Object by Pick up ⼝ surface (interface table) The pointer and Data pointer form .

runtiem.h

struct Iface
{
    
    Itab*    tab;
    void*    data;
};
struct Itab
{
    
    InterfaceType*    inter;
    Type*             type;
    void (*fun[])(void);
};

  The interface value is a two word data structure , The first word contains a pointer to the internal table . This internal table is called iTable, Contains the type information of the stored value .iTable Contains the type information of the stored value and a set of methods associated with the value . The second word is a Pointer to the stored value .


Sketch of interface value after entity value assignment :
 Insert picture description here


Sketch of interface value after entity pointer assignment :

 Insert picture description here

Four 、 Interface conversion

1、 Types of assertions

func test1(i interface{
    }) {
    
	if v, ok := i.(int); ok {
    
		fmt.Printf("type is int, value: %v", v)
	}
}

2、switch Make type batch judgment , I won't support it fallthrough.

func test2(i interface{
    }) {
    
	switch v := i.(type) {
    
	case nil:
		fmt.Println("this is nil")
	case int:
		fmt.Println("this is int: ", v)
	case string:
		fmt.Println("this is string: ", v)
	case float32:
		fmt.Println("this is float32: ", v)
	default:
		fmt.Println("unknow type")
	}
}

3、 A superset interface object can be converted to a subset interface , And vice versa .

type Peopler interface {
    
	Study()
	Animal
}

type Animal interface {
    
	Eating()
}

type Student struct {
    
	Name string
}

func (s Student) Study() {
    
	fmt.Println("I am study.")
}

func (s Student) Eating() {
    
	fmt.Println("I am Eating.")
}

func test3() {
    
	var p Peopler = Student{
    Name: "XiaoMing"}
	var a Animal = p
	a.Eating()
}

5、 ... and 、 Let the function implement the interface

type Tester interface {
    
	Do()
}

type FuncDo func()

func (self FuncDo) Do() {
     self() }

func test4() {
    
	var f Tester = FuncDo(func() {
     fmt.Println("hello world!") })
	f.Do()
}

版权声明
本文为[baboon_ chen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210546351237.html