go - object oriented (3)
go object oriented programming idea - Interface
Before we understand polymorphism, we must first learn about interfaces. In the golang language, we can say that interfaces are still the core idea of object-oriented programming
Basic introduction
The interface type can define a set of methods, but these do not need to be implemented. And the interface cannot contain any variables. When a user-defined type is selected, these methods will be written out in detail
Basic grammar
type Interface name interface{ method1(parameter list) Return value list method2(parameter list) Return value list } //Implement all methods of the interface type Custom type struct{ } type Custom type struct{ } func (t Custom type) method1(parameter list) Return value list{ //Method implementation } func (t Custom type) method2(parameter list) Return value list{ //Method implementation }
Explain
1. All the methods in the interface have no method body, that is, the methods of the interface are methods without implementation. The interface embodies the idea of polymorphism, high cohesion and low coupling in programming
2. The interface in Golang does not need to be explicitly implemented. As long as a variable contains all the methods in the interface type, the variable implements the interface. Because there is no keyword such as implement in Golang, in short, the interface implementation of Golang is based on methods. Interfaces are only used for scheduling. As long as methods can be implemented, they can be interfaced
Some details about interface implementation
1. The interface itself cannot create an instance, but it can point to a variable (instance) of a user-defined type that implements the interface
type Student struct{ Name string } func (stu Student) Say(){ fmt.Println("Hello") } func Ainterface interface{ Say() } func main(){ var stu Student var a Ainterface = stu A.Say() } //At this time, if there is no Student to implement this Say(), then this interface type cannot be implemented
2. In Golang, a user-defined type needs to implement all the methods of an interface before it can be said that the user-defined type implements the interface.
3. As long as it is a user-defined data type, you can implement the interface, not only the structure type
type integer int //Even though this integer defines the int type, it is still a method that can implement the interface func (i integer) Say(){ fmt.Println("say = ", i) } func main(){ var i integer = 10 var b Ainterface = i b.Say() }
4. An interface (such as interface A) can inherit multiple individual interfaces (such as interfaces B and C). If you want to implement interface A, you must also implement all the methods of interfaces B and C
5. The interface cannot have any variables
6. The interface type is a pointer (reference type) by default. If it is used without initializing the interface, nil will be output
ps: a small error
package main import "fmt" type Usb interface{ //Declare two methods that are not implemented Start() Stop() } type Phone struct{ } //How to make Phone implement Usb interface func (p *Phone) Start(){ //Notice the difference between the start and stop methods fmt.Println("Mobile phone starts working") } func (p Phone) Stop(){ fmt.Println("The mobile phone stops working") } func main(){ var p Phone var u Usb u = &p //If the method is a reference pointer, the reference to the interface also needs to use a pointer u.Start() }
Application scenarios of interfaces - benefits of interfaces
A small example of implementing sort
Let's check the source code of sort first
It can be seen from the above that a collection type satisfying the sort.Interface interface interface is required. If we do not define one at the beginning
package main import ( "fmt" "math/rand" "sort" ) //First, define a student structure type Student struct{ Name string class int score int } //Define a collection of student structs type Students []Student func main(){ var stus Students for i:=0;i<10;i++{ //Define ten student s with different scores stu := Student{ Name : fmt.Sprintf("student~%d",rand.Intn(100)), class : rand.Intn(10), score : rand.Intn(100), } stus = append(stus , stu) } for _,v := range stus{ fmt.Println(v) //Output array before arrangement } fmt.Println("----------------------See the effect---------------------------") sort.Sort(stus) for _,v := range stus{ fmt.Println(v) } }
Obviously, an error was reported, which probably means that the type of Students cannot be used, but! As long as we use the type of Students to implement the method required by the interface of sort, we can execute this function
So we improved the code
package main import ( "fmt" "math/rand" "sort" ) //First, define a student structure type Student struct{ Name string class int score int } //Define a collection of student structs type Students []Student //Check the source code. sort calls these methods. We use Students to implement it func (stus Students) Len() int{ return len(stus) } func (stus Students) Less(i, j int) bool{ return stus[i].score < stus[j].score } func (stus Students) Swap(i,j int){ stus[i],stus[j] = stus[j],stus[i] } func main(){ var stus Students for i:=0;i<10;i++{ //Define ten student s with different scores stu := Student{ Name : fmt.Sprintf("student~%d",rand.Intn(100)), class : rand.Intn(10), score : rand.Intn(100), } stus = append(stus , stu) } for _,v := range stus{ fmt.Println(v) //Output array before arrangement } fmt.Println("----------------------See the effect---------------------------") sort.Sort(stus) //Use Sort function directly for _,v := range stus{ fmt.Println(v) } }
The effect is very obvious. It is obvious that what the interface needs is more the implementation of methods, which reflects the object-oriented programming in golang. The important thing is the implementation of methods
Difference between inheritance and interface
The value of inheritance is more to solve the reusability and maintainability of code
The effect is very obvious. It is obvious that what the interface needs is more the implementation of methods, which reflects the object-oriented programming in golang. The important thing is the implementation of methods
Difference between inheritance and interface
The value of inheritance is more to solve the reusability and maintainability of code
The value of an interface is to design and design various specifications and methods, and let other user-defined types implement these methods.