Go core development study notes (twenty-four) - Interface, polymorphism, assertion

Interface Interface Overview

  1. Abound in Golang, the heart and soul of object-oriented programming interface must be, with respect to other OOP languages ​​are also very unique.
  2. Mobile phones, cameras connected to a computer USB port, are unified standard, do not worry about what in the end device connected to a computer, plug in what is what, which leads to the concept of polymorphism.
  3. Polymorphism is mainly dependent on the interface, the high-low coupled together.
  4. Interface defines the methods a few unrealized create other structures, complement each method, in order to achieve different structure similar to calling a "hub" to complete all the interface methods.
  5. ★★★ interface methods are not all constructs, i.e., the interface method is not implemented , the interface embodies the idea of polymorphism and high cohesion and low coupling programming.
  6. ★★★ golang interface does not require explicit realization, as long as a variable that contains all the basic methods, then the variable on the realization of this interface, there is no implement keyword.

Illustration, defines an interface

package main
import "fmt"

type Usb interface {
	/*
	声明了两个没有实现的方法
	 */
	Start()                  //定义接口类型与结构体类似
	Stop()                   //接口类型中只能定义方法!不能定义属性!
}

type Usb2 interface {
	/*
	声明了两个没有实现的方法
	 */
	Start()                  
	Stop()   
	Test()                   //下面所有结构体方法都没有Test(),没有实现就不可使用Usb2接口,一定会报错,必须要完全实现方法                
}

type Phone struct {

}

func (p Phone) Start() {
	fmt.Println("手机开始工作")
}

func (p Phone) Stop() {
	fmt.Println("手机停止工作")
}

type Camera struct {

}

func (c Camera) Start() {
	fmt.Println("相机开始工作")
}

func (c Camera) Stop() {
	fmt.Println("相机停止工作")
}

type Computer struct {

}

func (c1 Computer) Connect(usb Usb) {
	usb.Start()
	usb.Stop()
}

func main() {
	//创建结构体变量
	computer := Computer{}
	phone := Phone{}
	camera := Camera{}
	//重点
	computer.Connect(phone)
	computer.Connect(camera)
}

Interface Usage Scenario

  1. The development process can not be done by a programmer all the work, the project manager can provide an interface, consistent interface to all content, all methods each variable by the programmer responsible for implementation.
  2. It can be well controlled and managed software development progress.

Matters and interface details

  1. The interface itself can not create an instance, but can point to a custom type implements the interface variables. // The above example is not the interface itself Usb example, but Camera Phone, and may use the interface to create an instance method
  2. All interface methods are no method bodies, namely the method is not implemented.
  3. Golang in a custom type requires an interface! All methods! Have achieved, we say that this custom type implements the interface.
  4. As long as the custom type, you can implement the interface, not only the structure, int, float can be, provided that implements the interface as long as all the way!
  5. A custom type can implement multiple interfaces, as long as the realization of all the methods! // interface method A 1, B 2 interface method, a structure variable implements methods 1 and 2, then A and B interfaces and methods can be used to achieve full.
  6. Define the interface type must not contain any variable! Not only is the method to achieve!
  7. The interface can also be inherited, inherited the premise is to achieve all inherited inherited method!
  8. Interface is a reference type, with different structure, if the initialization is not used, the output is nil.
  9. Air Interface interface {} no way, so all data types have achieved empty interface, i.e., we can assign any variable to empty interfaces.
  10. ★★★ achieve the interface method must be noted that the method bind variable func (p phone) xx () {} and func (p * phone) xx () {} are two completely different concept, one is phone type of implementation, a phone is the corresponding pointer type implements a method behind if the interface variables involved, must correspond on, or certainly compilation errors.

Article IX For an example, look at the empty interface receives print out what value.

package main
import "fmt"
type T1 interface {

}

func main() {
	//没有初始化使用,打印出来是nil<nil>
	var t1 T1
	fmt.Println(t1)

	//给空接口传入一个整型
	num := 666
	var t2 T1 = num
	fmt.Println(t2)   //666 

	//直接定义空接口类型,直接实例化出一个t3空接口赋予num1
	var num1 = 8.8
	var t3 iterface{} = num1
	fmt.Println(t3)            //8.8
}

Interfaces and inheritance relations

  1. Interface can not achieve by defining the method, as a new variable after the succession of expansion, such as sword sword ho inherits all the Juggernaut, while opening the eyes realize new skills, new skills can be achieved by way of the interface.
  2. Implement supplementary interface inheritance mechanism, the interface provides common norms and standards.
  3. Mainly to solve the succession of code reusability and maintainability issues; the main interface to design a good variety of specifications that allow other custom types to implement this specification method.
  4. The interface is more flexible than inheritance, no similar inheritance is a hundred percent fit not is a, just like a can.
  5. Interface code decoupled to some extent.

Polymorphism

  1. Variables have a variety of forms, the third major feature of object-oriented, multi-state golang is achieved via the interface.
  2. Can follow different to achieve a unified interface calls, then the interface variables take on different forms.

Interface reflect Polymorphisms

  1. Polymorphic parameters: by passing the variable parameter to determine which implementation of the interface method.
  2. Polymorphic array: storing various polymorphic structures parameters involved in an array, wherein the structure also has its own unique method can be invoked, as detailed in the following assertion

Assert assert

  1. A structure variable is assigned to an empty port, and then specify a structure variable of the same type, the air interfaces assigned to this structure variable, do not do so directly (need type assertion)

    package main
    import "fmt"
    type Zuobiao struct {
    	x int
    	y int
    }
    
    type A interface {
    
    }
    
    func main() {
    	zuobiao := Zuobiao{3,5}
    	var a A
    	a = zuobiao
    	fmt.Println(a)
    	var zuobiao1 Zuobiao
    	//zuobiao1 = a            //返回来赋值是不可以的,
    	//这时候需要使用断言判断是否可以转换,如果不能转换就会报错,因为a指向zuobiao,所以可以转换成功。
    	zuobiao1 = a.(Zuobiao)    //如果希望把空接口重新转换成原类型,那么就要使用断言 <接口变量>.(<回转类型名称>)
    	fmt.Println(zuobiao1)
    }
    
  2. Type assertion: Because the interface is a general type, not a specific type, to be converted into a specific type, we need to use the type of assertion.

  3. Assertion is not random conversion, but empty interface variable to point to what type, you must use this type.

  4. How assertion checks were carried out, bring the detection mechanism, if success is ok, otherwise it will not report panic

    // detect the type of assertion with the wording 1

    var b A
    var zb2 = Zuobiao{6,7}
    b = zb2
    zb2,ok := b.(Zuobiao)     //ok本身是布尔类型,这里是重点
    if ok {                   //接下来条件判断,不会产生panic,而是根据判断继续流程控制
    	fmt.Println("OK,转换成功",zb2)
    } else {
    	fmt.Println("转换不成功,继续执行后续代码")
    }
    fmt.Println("断言已经判断,可以继续执行")
    

    // asserted band detection type 2 wording

    var b A
    var zb2 = Zuobiao{6,7}
    b = zb2
      
    if zb2,ok := b.(Zuobiao); ok {       //使用了if并列条件方式,结合了两句话,开发中也常用。
    	fmt.Println("OK,转换成功",zb2)
    } else {
    	fmt.Println("转换不成功,继续执行后续代码")
    }
    fmt.Println("断言已经判断,可以继续执行")
    

Case 1: The type of assertion frequently used where: A total structure variable interface in its own unique way, how to ensure the call

package main

import "fmt"

type Usb interface {
	/*
		声明了两个没有实现的方法
	*/
	Start()                  //定义接口类型与结构体类似
	Stop()                   //接口类型中只能定义方法!不能定义属性!
}

type Phone struct {

}
func (p Phone) Start() {
	fmt.Println("手机开始工作")
}
func (p Phone) Stop() {
	fmt.Println("手机停止工作")
}
func (p Phone) Call() {
	fmt.Println("手机可以打电话")
}

type Camera struct {

}
func (c Camera) Start() {
	fmt.Println("相机开始工作")
}
func (c Camera) Stop() {
	fmt.Println("相机停止工作")
}

type Computer struct {

}
func (c1 Computer) Connect(usb Usb) {
	usb.Start()
	//如果usb指向是一个phone结构体变量的,还需要使用call()方法
	//这时候添加类型断言,这个在今后开发中很重要,常用到
	if phone,ok := usb.(Phone) ; ok {       //phone对应变量可以随意定义,保证变量与<变量>.Call()一致即可
		phone.Call()                    //手机可以打电话,这种方式可以使每个独特方法的结构体增加美观性。
	}
	usb.Stop()
}

func main() {
	/*
	解决共有接口类型的数组结构体又分别有自己独特方法的解决方案
	 */
	var arrUsb [2]Usb
	arrUsb[0] = Phone{}
	arrUsb[1] = Camera{}
	var c1 Computer
	for _ , v := range arrUsb {
		c1.Connect(v)
	}
}

Case 2: Write a function to determine the type of incoming data and outputs the result, the focus is <array element> (type) use this assertion.

package main
import "fmt"
func TypeJudge (items ...interface{}) {           //传入可变长度类型的空接口
	for i , v := range items {                    //遍历所有传入参数所在数组
		switch v.(type) {                         //switch case循环判定类型为哪些
		case bool:
			fmt.Println(i," ",v,"为布尔类型")
		case string:
			fmt.Println(i," ",v,"为字符串类型")
		}
	}
}

func main() {
	/*
	定义一个可变参数的空接口
	 */
	var name = "shit"           //字符串
	var buer = false            //布尔
	TypeJudge(name,buer)
}
Published 49 original articles · won praise 18 · views 4003

Guess you like

Origin blog.csdn.net/weixin_41047549/article/details/90236402