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

Case Analysis of Go Interface Type assertion

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

Share

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

The editor today takes you to understand the example analysis of Go interface type assertions. The knowledge points in the article are introduced in great detail. Friends who think it is helpful can browse the content of the article with the editor, hoping to help more friends who want to solve this problem to find the answer to the problem. Let's follow the editor to learn more about "Go interface type assertion case analysis".

Go interface Interface

Definition: the Interface type can define a "group" method to represent the characteristics of an object. Interface cannot contain any variables.

Code:

Interface keyword

Define the interface type, which is a reference type

Is abstract, only concrete classes can call the

Type Aniaml interface {/ / defines two behavioral characteristics, the method Eat () Talk ()}

Define 2 struct

/ / as long as a specific struct implements all the methods of the type of the interface, that is, all the behavioral characteristics of the interface, can be stored in the interface type variable

Type Dog struct {Name string} type Cat struct {Name string} / / add two methods func (d * Dog) Eat () {fmt.Println (d.Name, "is eat")} func (D1 * Dog) Talk () {fmt.Println (d1.Name, "is Wangwang")} func main () {/ / variables of animal type interface type It can store any function that contains two concrete instances of type var an Aniaml / / dog var d Dog d.Eat () a = & d a.Eat ()}

Interface implementation

The interface in go does not need a displayed implementation, as long as an object implements all the methods of the interface type, then the object implements the interface

Remember to achieve all the methods!

If the object implements more than one method of type interface, then the object implements multiple interfaces

Test: type Aniaml interface {

Eat ()

Talk ()

} func TestOperator () {

/ / define a slice of the interface type:

Var animallist [] Aniaml

/ / instantiate

D: & Dog {

Name: "prosperous wealth"

}

Animallist = append (animallist,d)

D1: = & Dog {

Name: Gouzi

}

Animallist = append (animallist,d1)

C: = & Cat {

Name: "Meow 1"

}

Animallist = append (animallist,c)

C1: = & Cat {

Name: "Meow 2"

}

Animallist = append (animallist,c1)

For _, v:=range animallist {

V.Eat ()

V.Talk ()

}

}

Empty interface, Interface {}

Definition: empty interfaces have no methods, so all types implement empty interfaces

Package main

Import "fmt"

Func main () {

/ / empty interface, which can store both strings and int

Var an interface {}

Var b int = 100

A = b

Fmt.Println (a)

Var c string = "hello"

A = c

Fmt.Println (a)

}

Type assertion:

Definition: if we reverse to know which type of object this interface variable actually stores, we can use the following "forward" conversion

Var t int

Var x interface {}

X = t

Y, ok = x. (int) / / convert to int with check

Column two:

/ a. (type) get the type of variable

Switch t: = a. (type) {

Case * Dog:

T.Eat ()

Fmt.Printf ("t is dog\ n")

Case * Cat:

T.Eat ()

Fmt.Printf ("t is cat\ n")

}

Chestnut three:

Package mainimport ("fmt") func justify (items... interface {}) {for index, v: = range items {switch v. (type) {case int: fmt.Printf ("% d parameter is int\ n" Index) case int32: fmt.Printf ("% d parameter is int32\ n", index) case float32: fmt.Printf ("% d parameter is float32\ n" Index)}} func main () {var an int var b float32 var c int32 justify (a, b, c)}

Determine whether a variable implements the specified interface:

Chestnut:

/ / WeChatPay is a struct type

/ / pay is an interface

Type Pay interface {

Pay (user_id int64,money float64) error

}

Type WeChatPay struct {

}

Func (w * WeChatPay) pay (user_id int64,money float64) error {

Fmt.Println (WeChat Pay!!)

Return nil

}

/ / you should first save the weChat instance to an empty interface, and then use the empty interface to see if the interface is implemented.

WeChat: = & WeChatPay {}

Var tmp interface {} = weChat

, ok: = tmp. (Pay)

If ok {

Fmt.Println ("weChat is implement Pay interface")

/ / phone.OpenPay ("wechat_pay", weChat)

}

Chestnut:

Using the interface method to realize sort function

# check that the interfaces inside the system sort are these three interfaces.

Type Interface interface {

/ / Len is the number of elements in the collection.

Len () int

/ / Less reports whether the element with

/ / index i should sort before the element with index j.

Less (I, j int) bool

/ / Swap swaps the elements with indexes i and j.

Swap (I, j int)

}

So as long as we implement these three interfaces, we can use sort.

Package main

Import (

/ / "sort"

"math/rand"

"fmt"

"sort"

)

Type Student struct {

Name string

Age int

Source float32

}

Type StudentSlice [] * Student

Func (p StudentSlice) Len () int {

Return len (p)

}

Func (p StudentSlice) Less (iMagne j int) bool {

/ / fmt.Printf ("iMagnej\ n", iMagnej)

Return p [I] .age < p [j] .age

}

Func (p StudentSlice) Swap (iMagne j int) {

P [I], p [j] = p [j], p [I]

}

Func main () {

Var studentarr StudentSlice

For iPUR.

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