In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article introduces the relevant knowledge of "how to define the inheritance polymorphism of interface interface in go language". Many people will encounter this dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. What is an interface?
Interface is a kind of specification and standard, which is often seen in daily life, such as the USB interface of notebook computer, which can link the mouse and keyboard produced by any manufacturer with the computer. Why? The reason is that after the specification and standard are established by the USB interface, various manufacturers can produce mice and keyboards according to the standard.
In program development, interfaces only specify what to do and what to do. Exactly how to do it, the interface does not care. This is also similar to the case of interface in life, such as USB interface, which only specifies the standard, but doesn't care how the mouse and keyboard are produced according to the standard.
In enterprise development, if a project is large, you need an architect who can sort out all the business to define some of the major interfaces that tell the developer what functions you need to implement.
two。 Interface definition
The syntax of the interface definition is as follows:
Method 1: interface receives any data format / / define the interface first. Generally, it ends with er to implement the function type CurrencyEr2 interface {Symbol () string} according to the interface. Mode 2: specify the type type Currency string.
How to implement the methods defined in the interface?
Func (c Currency) Symbol () string {m: = "" switch c {case "CNY": / / RMB m = "¥" case "KRW": / / won m = "won" case "TWD": / / Taiwan dollar M = "$" case "JPY": / / yen m = "¥" case "USD": / / USD m = "$"} return m}
The specific calls are as follows:
Func main () {/ / method one: a:=CurrencyEr2 (Currency ("CNY")). Symbol () fmt.Println (a) / / method two: b:=Currency ("CNY"). Symbol () fmt.Println (b)}
As long as the class (structure) implements the corresponding interface, the objects created according to the class can be assigned to the corresponding interface type.
The naming convention of the interface ends with er.
3. Polymorphisms
What are the benefits of interfaces? Implement polymorphism.
Polymorphism is the same interface, using different instances to perform different operations.
Polymorphism refers to a variety of forms, as shown in the following figure:
Polymorphisms can be implemented using interfaces as follows:
Num1 int num2 int} / / add subclass structure type Add struct {Operate} / / implement addition subclass method func (a * Add) Result () int {return a.num1 + a.num2} / / subtract subclass structure type Sub struct {Operate} / / implement subtraction subclass method func (s * Sub) Result () int {return s.num1-s.num2} / / create One class is responsible for object creation / / factory class type Factory struct {} func (f * Factory) Result (num1 int) Num2 int Ch string) int {sum: = 0 switch ch {case "+": var an Add a.num1 = num1 a.num2 = num2 sum = Opter.Result (& a) case "-": var s Sub s.num1 = num1 s. Num2 = num2 sum = Opter.Result (& s)} return sum} / / call func main () {/ / create a factory object var f Factory aVL = f.Result (10) through design mode 20, "+") fmt.Println (a)} 4. Interface inheritance and transformation
Interfaces can also implement inheritance:
Package mainimport "fmt" / / defines the interface first generally ends with er to implement the function according to the interface type Humaner2 interface {/ / subset / method declaration sayhi ()} type Personer interface {/ / superset Humaner2 / / inherits sayhi () sing (string)} type student13 struct {name string age int score int} func (s * student13) sayhi () {fmt.Printf ("Hello, I am% s, this year% d years old" Func (s * student13) sing (name string) {fmt.Println ("I'll sing a song for you", name)} func main () {/ / Interface type variable definition var h Humaner2 var stu student13 = student13 {"Xiao Wu" 18 stu h.sayhi 59} h = & stu h.sayhi () / / Interface type variable definition var p Personer p = & stu p.sayhi () p.sing ("big bowl noodles")}
After the interface is inherited, you can implement the "superset" interface to transform the "subset" interface. The code is as follows:
Package mainimport "fmt" / / defines the interface first generally ends with er to implement the function according to the interface type Humaner2 interface {/ / subset / method declaration sayhi ()} type Personer interface {/ / superset Humaner2 / / inherits sayhi () sing (string)} type student13 struct {name string age int score int} func (s * student13) sayhi () {fmt.Printf ("Hello, I am% s, this year% d years old" Func (s * student13) sing (name string) {fmt.Println ("I'll sing a song for you", name)} func main () {/ / interface type variable definition var h Humaner2 / / subset var p Personer / / superset var stu student13 = student13 {"Xiao Wu" 18 stu 59} p = & stu / / assign an interface to another interface / / method with all subsets in the superset h = p / / ok h.sayhi () / / subset does not contain superset / / subset cannot be assigned to superset / / p = h / / err / / p.sayhi () / / p.sing ("bowl noodles")} 5. Null interface
Empty interfaces (interface {}) do not contain any methods, which is why all types implement empty interfaces, so empty interfaces can store values of any type.
For example:
Var i interface {} / / interface type can receive any type of data / / fmt.Println (I) fmt.Printf ("% T\ n", I) I = 10fmt.Println (I) fmt.Printf ("% T\ n", I)
When a function can accept any object instance, we will declare it as interface {}. The most typical example is the PrintXXX series of functions in the standard library fmt, such as:
Func Printf (fmt string, args... interface {}) func Println (args... interface {})
If you define the function yourself, you can do the following:
Func Test (arg... interface {}) {}
The Test () function can accept any number of arguments of any type.
6. Interface conversion
Conclusion: a superset can be converted into a subset, and a subset cannot be converted into a superset.
Package mainimport "fmt" type Humaner interface {/ / subset sayhi ()} type Personer interface {/ / superset Humaner / / anonymous field Inherited sayhi () sing (lrc string)} type Student struct {name string id int} / / Student implemented sayhi () func (tmp * Student) sayhi () {fmt.Printf ("Student [% s,% d] sayhi\ n", tmp.name, tmp.id)} func (tmp * Student) sing (lrc string) {fmt.Println ("Student is singing:" Lrc)} func main () {/ / superset can be converted to a subset Conversely, var iPro Personer / / superset iPro = & Student {"mike", 666} var i Humaner / / subset / / iPro = I / / err I = iPro / / Yes, superset can be converted into subset i.sayhi ()} 7. Implement the map dictionary interface package mainimport ("fmt"sync") type UserAges struct {ages map [string] int sync.Mutex} func (u * UserAges) Add (name string,age int) {u.Lock () defer u.Unlock () u.ages [name] = age} func (u * UserAges) Get (name string) int {if age,ok:=u.ages [name] Ok {return age} return-1} func main () {dic:=make (map [string] int) dic ["age"] = 18 r:=UserAges {ages: dic} r.Add ("jeff") 20) fmt.Println (r) age:=r.Get ("age") fmt.Println (age)} 8.interface case package mainimport "fmt" type Bike interface {save () update () insert ()} type User struct {name string} func (this * User) save () {fmt.Println ("saved successfully" This.name)} func (this * User) update () {fmt.Println ("updated successfully", this.name)} func (this * User) insert () {fmt.Println ("inserted successfully" This.name)} func main () {var data Bike = & User {name: "jeff"} data.save () data.update () data.insert ()} "how to define the inheritance Polymorphism of interface Interface in go language" ends here Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.