Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

The usage of Interface in go language

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the knowledge of "the use of interfaces 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!

Catalogue

one。 Other languages

II. Go language

3. Polymorphisms are implemented with go interface

four。 Use of empty interfaces (key points)

4.1 definition

4.2 use of empty interface

4.3 several holes to pay attention to in the empty interface (my mistake when I was just learning)

one。 Other languages

Interface concept provided in other languages: interfaces exist primarily as contracts between different components. The implementation of the contract is mandatory (intrusive interface), and you must declare that you do implement the interface. In order to implement an interface, you need to inherit from that interface.

Interface IFoo {

Void Bar ()

}

/ / Java grammar / /.

Class Foo implements IFoo {

}

/ / C++ grammar / /.

Class Foo: public IFoo {

}

The main manifestation of "intrusive" is that the implementation class needs to explicitly declare that it has implemented an interface.

II. Go language

The interface in go language is also slightly different from that in other languages. It is a non-intrusive interface. When you implement a class, you only need to care about what methods you should provide, and you don't have to worry about how detailed the interface needs to be. The interface is defined by the user on demand without prior planning. A class only needs to implement all the functions required by the interface, so let's say that the class implements the interface.

The implementation of the type Phone interface {call ()} type Nokia struct {name string} / / interface is the implicit func (phone Nokia) call () {fmt.Println ("I am Nokia" Is a phone ")} III. Go Interface implements polymorphic package mainimport (" fmt "" strconv ") / / defines 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 purchase "+ strconv.Itoa (phone.quantity) + strconv.Itoa (phone.settleAccount ()) + "Yuan"} 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 purchase" + strconv.Itoa (gift.quantity) + "+ gift.name +" count: "+ strconv.Itoa (gift.settleAccount ()) +" Yuan "} 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: "headphones", quantity: 1, price: 200 } goods: = [] Good {iPhone, earphones} allPrice: = calculateAllPrice (goods) fmt.Printf ("this order requires a total payment of% d yuan", allPrice)} four. Use of null interfaces (focus) 4.1 definition

Empty interfaces do not have any method ports defined, so we can say that all types at least implement empty interfaces.

Each interface contains two properties, one is the value and the other is the type.

For empty interfaces, both are nil, which can be verified using fmt

Package mainimport ("fmt") func main () {var i interface {} fmt.Printf ("type:% T, value:% v", I, I)}

Clients / type:, value:

4.2 use of empty interface

First, we usually directly use interface {} as the type to declare an instance, and this instance can hold any type of value.

/ / declare an empty interface instance var i interface {} / store int no problem I = 1 fmt.Println (I) / store string I = "hello" fmt.Println (I) / / store Boolean value I = false fmt.Println (I)

Second, if you want your function to receive any type of value, you can also use an empty interface

Third, you also define one that can receive any type of array, slice, map, strcut, for example, a slice is defined here.

Func main () {any: = make ([] interface {}, 5) any [0] = 11 any [1] = "hello world" any [2] = [] int {11,22,33,44} for _, value: = range any {fmt.Println (value)}} 4.3 empty interface several holes to pay attention to (a mistake I made when I was just learning)

Pit 1: an empty interface can carry any value, but it does not mean that any type can accept the value of an empty interface type.

/ / declare a variable, type int, initial value 1 var an int = 1 / / declare I variable, type interface {}, initial value a, then change the value of I to 1 var i interface {} = a / / declare b variable, try to assign I error var b int = I

Pit 2: when the empty interface carries arrays and slices, the object can no longer be sliced

Sli: = [] int {2,3,5,7,11,13} var i interface {} I = sli / / error g: = I [1:3] fmt.Println (g)

Pit 3: when you use an empty interface to receive any type of parameter, its static type is interface {}, but the dynamic type (int,string or other types) we don't know, so we need to use type assertions.

There is also a point to explain the implicit conversion of func myfunc (I interface {}) {switch I. (type) {case int: fmt.Println ("parameter type is int") case string: fmt.Println ("parameter type is string")} func main () {a: = 10b: = "hello" myfunc (a) when an empty interface calls a function. Myfunc (b) error / * switch a. (type) {case int: fmt.Println ("the type of parameter is int") case string: fmt.Println ("type of parameter is string") * /} "usage of interfaces in go language". 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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report