当前位置:网站首页>Go interface Foundation

Go interface Foundation

2022-07-28 08:54:00 go|Python

go Interface Basics

In the field of object-oriented , Interfaces are generally defined like this : Interface defines the behavior of an object . The interface only specifies what the object should do , As for how to achieve this behavior ( That's the implementation details ), It's up to the object itself .

stay Go In language , An interface is a method signature (Method Signature) Set . When a type defines all the methods in the interface , We say it implements the interface . This is similar to object-oriented programming (OOP) It's very similar . Interface specifies the method that a type should have , And it's up to the type to decide how to implement these methods .

With python Take the duck type as an example : If there is a duck's way of walking in the class , The way ducks talk , No matter what kind you are , You are all duck type .

class Duck:   #  Define duck type 
    def speak(self):
        pass
        
    def run(self):
        pass
        
class Cat#  Although there is no inheritance Duck class , however Cat Namely Duck This type 
    def speak(self):
        pass

    def run(self):
        pass	

Popular point theory : There is no need for explicit inheritance , As long as you have Duck Methods in class , You are the one Duck Subclasses of classes

stay go In language , There is also the concept of duck type , We call it an interface (interface)

Definition of interface

  • An interface is actually a type
//  Defining interfaces   An interface is a collection of methods   But it didn't work   The object needs to implement itself 
type Duck interface {
    
	speak(s string)
	run()
}

Implementation and use of interface

func main() {
    
	tduck := TDuck{
    " Donald Duck 1 Number ", 4}
	tduck.speak(" The most stupid ")    //  Donald said :  My name is   Donald Duck 1 Number   I am a   The most stupid 
	tduck.run()				//  Donald Duck 1 Number   Walk awkwardly 

}


//  Defining structure 
type TDuck struct {
    
	name string
	age int
}

type PDuck struct {
    
	name string
	age int
}
//  Donald Duck , Realization speak and run
func (t TDuck) speak(s string)  {
    
	fmt.Println(" Donald said :  My name is  ", t.name, " I am a ", s)
}

func (t TDuck) run()  {
    
	fmt.Println(t.name," Walk awkwardly ")
}


//  Ordinary duck , Realization speak and run
func (t PDuck)speak(s string)  {
    
	fmt.Println(" I am an ordinary duck , My name is :",t.name," I said, :",s)
}
func (t PDuck)run()  {
    
	fmt.Println(" I am an ordinary duck , My name is :",t.name," I walk askew ")
}

 Insert picture description here

It should be noted that , stay go Implementation of interface in , All methods in the interface must be implemented , Only then can the logo in the above figure appear , Even if only one method is not implemented , It is not an implementation interface .
 Insert picture description here

The practical use of the interface

TDuck Realized Duck Interface , therefore TDuck All of them are Duck Object of type , I can assign a value to Duck Object of type , But you can only use methods in the interface , You cannot use specific types of attributes .

func main() {
    
	tduck := TDuck{
    " Donald Duck 1 Number ", 4}
	tduck.speak(" The most stupid ")  //  Donald said :  My name is   Donald Duck 1 Number   I am a   The most stupid 
	tduck.run()				//  Donald Duck 1 Number   Walk awkwardly 
	test5(tduck," The most stupid ")  //  The ginseng 
    var duck Duck
    duck = tduck  //  Direct assignment 
}

func test5(d Duck, s string)  {
    
	d.run()  //  Donald said :  My name is   Donald Duck 1 Number   I am a   The fiercest 
	d.speak(s)  //  Donald Duck 1 Number   Walk awkwardly 
}

Empty interface and anonymous empty interface

An interface that does not contain a method is called an empty interface . An empty interface is represented as interface{}. Because there is no method for an empty interface , So all types implement empty interfaces .

type Panada interface {
    }
func PrintPa(i Panada) {
    
	fmt.Printf("Type = %T, value = %v\n", i, i)
}

func main() {
    
	PrintPa(10)  // Type = int, value = 10
	PrintPa("lxx")   // Type = string, value = lxx
	PrintPa([3]int{
    1,2,3})  // Type = [3]int, value = [1 2 3]
}

Anonymous empty interface , It's simply an empty interface without a name , Use only once , It is written as follows

func PrintPa(i interface {
    }) {
    
	fmt.Printf("Type = %T, value = %v\n", i, i)
}

Types of assertions

Type assertions are used to extract the underlying values of the interface , In grammar i.(T) in , Interface i The specific type of the new model is T, This syntax is used to get the underlying value of the interface . Used to solve in function , Use when you need to use the properties of the structure object that implements this interface . The code is as follows

func main() {
    
	tduck := TDuck{
    " Donald Duck 1 Number ", 4}
	test5(tduck," The most stupid ")
}

func test5(d Duck, s string)  {
    
	d.run()
	d.speak(s)
	//  Interface objects have only methods , There is no specific type (tduck) Properties of 
	//fmt.Println(d.name) //  Report errors 
	v,ok := d.(TDuck)   
    // ok  by  true when , Assert success , by false Assertion failed 
    //  You can also use  v := d.(TDuck)  How to write it , But this way of writing will throw exceptions once the assertion fails , Not recommended 
	if ok {
    
		fmt.Println(v.name)  //  Donald Duck 1 Number 
		fmt.Println(v.age)   // 4
	}
}

Type selection

Type selection is used to associate specific types of interfaces with many case Statement . It's with the general switch Statements like . The only difference is that type selection specifies the type , And general switch The specified value is .

The syntax of type selection is similar to type assertion . The syntax of type assertion is i.(T), And for type selection , type T By keyword type Instead of .

func main() {
    
	tduck := TDuck{
    " Donald Duck 1 Number ", 4}
	pduck := PDuck{
    " Old duck 1 Number ", 4}
	test6(tduck, " The most stupid ")
	test6(pduck, " The most ignorant ")

}

func test6(d Duck, s string) {
    
	switch obj := d.(type) {
    
	case TDuck:
		obj.run()
		fmt.Println(obj.name)
	case PDuck:
		obj.speak(s)
		fmt.Println(obj.age)
	}
}

Add :

  1. The zero value of the interface is nil So the interface is a reference type
  2. The underlying implementation of the interface points to a specific type through a pointer (type : value)type It's the specific type of the underlying interface (Concrete Type), and value Is the value of a specific type .
var duck Duck
fmt.Println(duck)   // <nil>
原网站

版权声明
本文为[go|Python]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/197/202207131439144428.html