当前位置:网站首页>Go language - Interface

Go language - Interface

2022-06-21 15:38:00 Crying while learning

summary

Only methods are defined in the interface , There is no concrete implementation of the method . Method code needs types to implement .

If a structure is defined , To implement the methods in the interface . Then this structure is the implementation of the interface .

  1. When an interface type object is required , You can use any implementation class object instead of .
  2. Interface objects cannot call fields of implementation classes .

Function of interface

  1. The function of the interface is decoupling . When modifying part of the code , Other parts of the code are least affected .
  2. Interface is the separation of function definition and function implementation .
  3. Through interface , It can simulate the polymorphism of object-oriented language .

grammar

//1. Defining interfaces 
type interface_name interface {
    method_name1 [return_type]
    method_name2 [return_type]
    ...
}

// Defining structure 
type struct_name1 struct {
     Field name      Field type 
}

// Implementation interface method 
func (variable struct_name1) method_name1(parameter list) (return list) {
     Method realization 
}

func (variable struct_name1) method_name2(parameter list) (return list) {
     Method realization 
}

Simulate one USB Interface . Realization start() and stop() Method . Two different structures implement mouse and storage ( Of the phenomenon object polymorphic ).

// Interface 
type USB interface {
	start()
	stop()
}

// Mouse structure 
type Mouse struct {
	name string
}

// Flash memory structure 
type FlashDisk struct {
	name string
}

// Structure method 
func (m Mouse) start() {
	fmt.Println(m.name, " The mouse starts to work ...")
}

func (m Mouse) stop() {
	fmt.Println(m.name, " The mouse stops working ...")
}

func (f FlashDisk) start() {
	fmt.Println(f.name, " Flash memory inserted , You can start using ...")
}

func (f FlashDisk) stop() {
	fmt.Println(f.name, " Flash memory unplugged ...")
}

// The test method 
func testInterface(usb USB) {
	usb.start()
	usb.stop()
}

func main() {
	mouse1 := Mouse{" Thunder snake super mouse "}
	flashDisk1 := FlashDisk{"15TB Super flash "}

	testInterface(mouse1)
	testInterface(flashDisk1)

	var usb USB = Mouse{" Logitech mouse "}
	usb.start()
	usb.stop()
}

 

Empty interface

Empty interface : Interfaces that do not contain any methods .

All types implement empty interfaces , Because of this , An empty interface type can store values of any type .

effect : Empty interface types can be defined , Definition array、slice、map, Type is empty interface type . You can store any type of value .

An empty interface type stores values of any type

// Interface 
type A interface {
}

// Structure 
type Animal struct {
	name string
}

type People struct {
	name string
	age  int
}

func main() {
	var a1 A = Animal{"minacat"}
	var a2 A = People{"liqi", 18}
	var a3 A = "aaa"
	var a4 A = 555
	fmt.Printf("a1 Value :%v, a1 The type of :%T\n", a1, a1)
	fmt.Printf("a2 Value :%v, a2 The type of :%T\n", a2, a2)
	fmt.Printf("a3 Value :%v, a3 The type of :%T\n", a3, a3)
	fmt.Printf("a4 Value :%v, a4 The type of :%T\n", a4, a4)
}

array、slice、map The type definition is an empty interface

func main() {
	//map, key character string ,value Any type 
	map1 := make(map[string]interface{})
	map1["name"] = " Zhang San "
	map1["age"] = 18
	map1["friend"] = []string{" Li Si ", " Wang Wu "}
	fmt.Printf("map value :%v, map type :%T\n", map1, map1)

	// section , Store any type 
	slice1 := []interface{}{1, " Zhang San ", true}
	fmt.Printf(" Slice value :%v,  Slice type :%T\n", slice1, slice1)

	// Array , Store any type 
	array1 := [3]interface{}{2, " Li Si ", true}
	fmt.Printf(" Array value :%v,  An array type :%T\n", array1, array1)
}

Interface nesting ( Inherit )

Interfaces are multi inherited , A class can inherit multiple parent classes .

As shown in the figure , Interface C Inherited interface A(test1() Method ) And interface B(test2() Method ), Interface C Own test3() Method . So implement the interface C It needs to be implemented at the same time A\B\C Methods of three interfaces .

You can define a structure , Realization A\B\C Methods of three interfaces . Which interface implementation is this structure , Depends on the type of variable declaration .

// Interface A
type A interface {
	test1()
}

// Interface B
type B interface {
	test2()
}

// Interface C, Inherited interface A/B
type C interface {
	A
	B
	test3()
}

// Structure 
type Xtest struct {
}

// Method realization 
func (x Xtest) test1() {
	fmt.Println("test1() Method ...")
}

func (x Xtest) test2() {
	fmt.Println("test2() Method ...")
}

func (x Xtest) test3() {
	fmt.Println("test3() Method ...")
}

func main() {
	var x1 Xtest = Xtest{}

	fmt.Println("-- Interface A The implementation of the --") // Only test1 Method , Unable to call test2、test3 Method 
	var a1 A = x1
	a1.test1()

	fmt.Println("-- Interface B The implementation of the --") // Only test2 Method , Unable to call test1、test3 Method 
	var b1 B = x1
	b1.test2()

	fmt.Println("-- Interface C The implementation of the --") // You can call test1、test2、test3 Method 
	var c1 C = x1
	c1.test1()
	c1.test2()
	c1.test3()
}

Interface assertion

Get the real type accepted by the interface

Grammar 1 :

Determine whether the interface object is an actual type , Yes, the Boolean parameter is true, conversely false.

 Variable parameters ,  Boolean parameters  :=  Interface object .( Actual type )

Grammar II :

Realize polymorphic processing for different structures .

switch  Variable parameters  :=  Interface object .(type) {
    case  Actual type 1:
        ...
    case  Actual type 2:
        ...
}

// Interface 
type USB interface {
	start()
	stop()
}

// Mouse structure 
type Mouse struct {
	name string
}

// Flash memory structure 
type FlashDisk struct {
	name string
}

// Structure method 
func (m Mouse) start() {
	fmt.Println(m.name, " The mouse starts to work ...")
}

func (m Mouse) stop() {
	fmt.Println(m.name, " The mouse stops working ...")
}

func (f FlashDisk) start() {
	fmt.Println(f.name, " Flash memory inserted , You can start using ...")
}

func (f FlashDisk) stop() {
	fmt.Println(f.name, " Flash memory unplugged ...")
}

// The test method 
func testInterface(usb USB) {
	switch instaceType := usb.(type) {
	case Mouse:
		fmt.Println(" You connected the mouse , Checking initialization driver ...")
		instaceType.start()
		instaceType.stop()
	case FlashDisk:
		fmt.Println(" You access storage , Scanning disk ...")
		instaceType.start()
		fmt.Println(" You can unplug the storage at any time ...")
		instaceType.stop()
	}
}

func main() {
	mouse1 := Mouse{" Thunder snake super mouse "}
	flashDisk1 := FlashDisk{"15TB Super flash "}

	testInterface(mouse1)
	fmt.Println("------------------")
	testInterface(flashDisk1)
}

 

原网站

版权声明
本文为[Crying while learning]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211239019939.html