Go language basic interface, empty interface, type assertion

The interface
in the Go language is a type, an abstract type, an interface is a collection of methods (methods), an interface is like defining a protocol, a rule, as long as a machine has laundry and dumping The dry function is called a washing machine. We don’t care about attributes, but only care about
the conditions of the behavior interface implementation.
As long as an object implements all the methods in the interface, then the interface is implemented. In other words, the interface is a list of methods that need to be implemented.
Interface type variables The
interface type can store all instances that implement the interface,
and the relationship between the type and the interface.
A type can implement multiple interfaces at the same time
. The values ​​of these interfaces are independent interfaces.
The storage of the interface is divided into two parts, one part is specific Type, one part is the value of the specific type, these two parts are called dynamic type and dynamic value.

package main

import "fmt"
//定义一个接口
type pp interface {
    
    
    run()
}

type person struct {
    
    
    name string
    age  int
}
func (p *person) run() {
    
    
    fmt.Println("跑")
}
type print struct {
    
    
    name string
}
func (p print) run() {
    
    
    fmt.Println("跑不了")
}
func main() {
    
    
    p := &person{
    
    
        "dlq",
        21,
    }
    //初始化接口
    pp1 := pp(p)
    pp1.run()
    p1 := print{
    
    
        "zkj",
    }
    //接口类型可以存储所有类型的实力
    //当类型下的函数,为指针就守着,那么存到接口中的也应该为指针类型
    pp2 := pp(p1)
    pp2.run()
}

Nesting of interfaces, relationship between types and interfaces, empty interfaces, type assertions

package main

import "fmt"
type pp1 interface {
    
    
    run()
}
type pp2 interface {
    
    
    move()
}
//接口的嵌套,那么这个切口就拥有所有嵌套的接口中的方法
type pp3 interface {
    
    
    pp1
    pp2
}
type person struct {
    
    
    name string
    age  int
}
func (p *person) run() {
    
    
    fmt.Println("run")
}
func (p *person) move() {
    
    
    fmt.Println("move")
}
//一个类型可以同时实现多个接口,接口之间是独立的
func main() {
    
    
    p := &person{
    
    }
    pp1 := pp1(p)
    pp2 := pp2(p)
    pp1.run()
    pp2.move()
    pp3 := pp3(p)
    pp3.move()
    //空接口
    mapp := map[string]interface{
    
    }{
    
    
        "name":  "dlq",
        "age":   12,
        "hobby": []string{
    
    "吃", "喝", "玩", "乐"},
    }
    fmt.Println(mapp)
    x := mapp["hobby"]
    //类型断言,判断一个变量是不是你想要的值
    v, ok := x.([]string)
    if !ok {
    
    
        fmt.Println("这个变量不是[]string类型")
    }
    fmt.Println(v)
}

Guess you like

Origin blog.csdn.net/weixin_44865158/article/details/114702401