Hi, Hello, this is Mingo.
During my time of learning Golang, I wrote detailed study notes on my personal WeChat official account "Go programming time". For Go language, I am also a beginner, so writing things should be more suitable for students who are just in contact. If you are just learning Go language, do not pay close attention to it, learn together and grow together.
My online blog: http://golang.iswbm.com
My Github: github.com/iswbm/GolangCodingTime
0. What is the interface?
This is an excerpt from Go language Chinese website
In the object-oriented field, interfaces are generally defined as follows: interfaces define the behavior of an object. The interface only specifies what the object should do, and how to implement this behavior (i.e. implementation details) is determined by the object itself.
In Go, an interface is a collection of method signatures. When a type defines all the methods in the interface, we call it the implementation of the interface. This is very similar to the term object-oriented programming (OOP). The interface specifies the methods that a type should have, and it's up to the type to decide how to implement them.
1. How to define interfaces
Use the type keyword to define the interface.
The following code defines a telephone interface, which requires that the call method be implemented.
type Phone interface { call() }
2. How to implement the interface
If there is a type / structure that implements all the methods required by an interface, there is only call method for the Phone interface, so as long as the call method is implemented, we can call it the Phone interface.
If there is a machine that can call others, then we can call it telephone.
The implementation of this interface is implicit, unlike JAVA, which uses implements to display instructions.
To continue with the phone example above, we first define a Nokia structure, which implements the call method, so it is also a phone.
type Nokia struct { name string } // Received by Nokia func (phone Nokia) call() { fmt.Println("I am Nokia,It's a phone") }
3. Interface implementation polymorphism
The definition of Duck typing is that as long as you look like a duck and call like a duck, I think you are a duck.
Take a popular example
What kind of person can be called a teacher?
Different people have different standards. Some people think that they must have a certain degree of education. Some people think that they must have a teacher's qualification certificate.
And I think as long as we can educate people and impart knowledge to others, we can call them teachers.
No matter what subject you teach? Sports or cooking.
No matter how you teach? Is it to teach in the classroom, with chalk, or to pursue the reality, direct practice.
It doesn't matter.
This is the different performance of different objects (people) under one interface (teacher). This is polymorphism.
In Go language, polymorphism is realized through interface.
Here to write a code to demonstrate the commodity interface.
First, define the interface of a Good, which means a type or structure. As long as two methods, settleAccount() and orderInfo(), are implemented, the type / structure is a product.
type Good interface { settleAccount() int orderInfo() string }
Then we define two structures: mobile phones and giveaways.
type Phone struct { name string quantity int price int } type FreeGift struct { name string quantity int price int }
And then implement two methods of Good interface for them
// Phone func (phone Phone) settleAccount() int { return phone.quantity * phone.price } func (phone Phone) orderInfo() string{ return "You want to buy" + strconv.Itoa(phone.quantity)+ "individual" + phone.name + "Total:" + strconv.Itoa(phone.settleAccount()) + "element" } // FreeGift func (gift FreeGift) settleAccount() int { return 0 } func (gift FreeGift) orderInfo() string{ return "You want to buy" + strconv.Itoa(gift.quantity)+ "individual" + gift.name + "Total:" + strconv.Itoa(gift.settleAccount()) + "element" }
After implementing the two methods required by the Good interface, mobile phones and gifts are all Good types in the view of Go language.
Here, I have selected two products (instantiation), namely mobile phone and headset (free, no money)
iPhone := Phone{ name: "iPhone", quantity: 1, price: 8000, } earphones := FreeGift{ name: "headset", quantity: 1, price: 200, }
Then create a shopping cart (that is, a slice of type Good) to store the items.
goods := []Good{iPhone, earphones}
Finally, define a method to calculate the order amount in the shopping cart
func calculateAllPrice(goods []Good) int { var allPrice int for _,good := range goods{ fmt.Println(good.orderInfo()) allPrice += good.settleAccount() } return allPrice }
The complete code, I paste below for your reference.
package main import ( "fmt" "strconv" ) // Define an interface type Good interface { settleAccount() int orderInfo() string } type Phone struct { name string quantity int price int } func (phone Phone) settleAccount() int { return phone.quantity * phone.price } func (phone Phone) orderInfo() string{ return "You want to buy" + strconv.Itoa(phone.quantity)+ "individual" + phone.name + "Total:" + strconv.Itoa(phone.settleAccount()) + "element" } type FreeGift struct { name string quantity int price int } func (gift FreeGift) settleAccount() int { return 0 } func (gift FreeGift) orderInfo() string{ return "You want to buy" + strconv.Itoa(gift.quantity)+ "individual" + gift.name + "Total:" + strconv.Itoa(gift.settleAccount()) + "element" } func calculateAllPrice(goods []Good) int { var allPrice int for _,good := range goods{ fmt.Println(good.orderInfo()) allPrice += good.settleAccount() } return allPrice } func main() { iPhone := Phone{ name: "iPhone", quantity: 1, price: 8000, } earphones := FreeGift{ name: "headset", quantity: 1, price: 200, } goods := []Good{iPhone, earphones} allPrice := calculateAllPrice(goods) fmt.Printf("This order needs to be paid in total %d element", allPrice) }
After operation, the output is as follows
You want to buy an iPhone: 8000 yuan You want to buy 1 headset: 0 yuan The order will cost 8000 yuan in total
Series Guide
01. Construction of development environment (GoLand & vs Code)
02. Learn how to create five variables
03. Detailed data type: * * * * integer and floating point
04. Detailed data types: byte, run and string
05. Explain data type: array and slice
06. Explain data types: dictionary and Boolean
07. Explain data type: pointer
08. Object oriented programming: structure and inheritance
09. An article to understand the functions in Go
10. Go language flow control: if else conditional statement
11. Go language process control: switch case selection statement
12. Go language process control: for loop statement
13. Go language process control: goto jump unconditionally
14. Go language process control: defer call
15. Object oriented programming: interface and polymorphism
16. Keyword: the difference between make and new?
17. An article understanding statement block and scope in Go
18. Learning Go process: goroutine
19. Learn Go protocol: explain channel / channel in detail
20. Detailed explanation of several channel deadlock classic error cases
22. Learning Go protocol: mutex lock and read-write lock
23. Exception handling in go: panic and recover
24. Super detailed interpretation of Go Modules' past life, present life and introduction
25. Eight knowledge points about package import in go language
26. How to open source the modules written by yourself for others?
27. What about type assertions in the Go language?
28. These five points lead you to understand the select usage of Go language