千家信息网

Go接口类型断言实例分析

发表于:2024-10-26 作者:千家信息网编辑
千家信息网最后更新 2024年10月26日,小编今天带大家了解Go接口类型断言实例分析,文中知识点介绍的非常详细。觉得有帮助的朋友可以跟着小编一起浏览文章的内容,希望能够帮助更多想解决这个问题的朋友找到问题的答案,下面跟着小编一起深入学习"Go
千家信息网最后更新 2024年10月26日Go接口类型断言实例分析

小编今天带大家了解Go接口类型断言实例分析,文中知识点介绍的非常详细。觉得有帮助的朋友可以跟着小编一起浏览文章的内容,希望能够帮助更多想解决这个问题的朋友找到问题的答案,下面跟着小编一起深入学习"Go接口类型断言实例分析"的知识吧。

Go接口 Interface

定义:Interface类型可以定义⼀组⽅法,⽤来表示⼀个对象的⾏为特征。 interface不能包含任何变量。

代码:

  1. interface关键字

  2. 定义接口类型,接口是引用类型

  3. 是抽象的,具体的类才可以调用

type Aniaml interface {    //定义2个是行为特征,方法    Eat()    Talk()}

定义2个struct

//只要一个具体的struct实现这个接口的类型的所有方法,也就是具有这个接口的所有行为特征,都是可以存储到这个接口类型变量里面

type Dog struct{    Name string}type Cat struct{    Name string}//添加2个方法func (d *Dog) Eat()  {    fmt.Println(d.Name,"is eat")}func (d1 *Dog) Talk()  {    fmt.Println(d1.Name,"is 旺旺")}func main(){    //那a animal类型的接口类型的变量,它里面就可以存储任何这个 函数包含着2个类型     var a Aniaml    //dog具体的实例     var d Dog     d.Eat()          a = &d     a.Eat()}

接口实现

go中的接口,不需要显示的实现,只要一个对象,实现了接口类型的所有方法,那么这个对象就实现了这个接口

记住是实现所有方法!!!!

如果应该对象实现了多个interface类型的方法,那么这个对象就实现了多个接口

测试:type Aniaml interface {

Eat()

Talk()

}func TestOperator() {

//定义一个接口类型的切片:

var animallist []Aniaml

//实例化

d := &Dog{

Name:"旺财",

}

animallist = append(animallist,d)

d1 := &Dog{

Name:"狗子",

}

animallist = append(animallist,d1)

c := &Cat{

Name:"喵喵1",

}

animallist = append(animallist,c)

c1 := &Cat{

Name:"喵喵2",

}

animallist = append(animallist,c1)

for _,v:=range animallist{

v.Eat()

v.Talk()

}

}

空接口,Interface{}

定义:空接口没有任何方法,所以所以类型都实现了空接口

package main

import "fmt"

func main() {

//空接口, 既可以存字符串又可以存int

var a interface{}

var b int = 100

a = b

fmt.Println(a)

var c string =" hello "

a = c

fmt.Println(a)

}

类型断言:

定义:如果我们反向要知道这个接口变量⾥⾯实际存储的是哪个类型的对象可以采⽤以下⽅法进⾏转换

var t int

var x interface{}

x = t

y, ok = x.(int) //转成int,带检查

列子二:

////a.(type) 获取变量的类型

switch t := a.(type) {

case *Dog:

t.Eat()

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

case *Cat:

t.Eat()

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

}

栗子三:

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

判断一个变量是否实现了指定接口:

栗子:

//WeChatPay 是一个struct类型,

//pay是一个接口

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("微信支付!!")

return nil

}

//应该先把weChat实例存到一个空的接口,然后使用空的interface 是否实现了这个接口

weChat := &WeChatPay{}

var tmp interface{} = weChat

_, ok := tmp.(Pay)

if ok {

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

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

}

栗子:

  1. 使用接口的方法实现sort功能

###查看系统sort内部的接口 是这3个接口.

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)

}

所以咱只要实现了这3个接口,就可以能用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(i,j int) bool {

//fmt.Printf("i,j\n",i,j)

return p[i].age < p[j].age

}

func (p StudentSlice) Swap(i,j int) {

p[i],p[j] = p[j],p[i]

}

func main() {

var studentarr StudentSlice

for i:=0;i<10;i++{

var s = &Student{

name :fmt.Sprintf("任%d",i),

age: rand.Intn(100),

source:rand.Float32() * 100,

}

studentarr = append(studentarr, s)

}

//系统的sort

//sort.Sort(studentarr)

//自定义的sort

site_sort(studentarr)

for i:=0;i

fmt.Printf("%#v\n",studentarr[i])

}

}

栗子2:

package main

type SortInterface interface {

Len() int

Less(i,j int) bool

Swap(i,j int)

}

func site_sort(a SortInterface) {

for i :=a.Len() -1 ;i>0;i--{

for j:=0;i

if a.Less(j+1,j){

a.Swap(j,j+1)

}

}

}

}

感谢大家的阅读,以上就是"Go接口类型断言实例分析"的全部内容了,学会的朋友赶紧操作起来吧。相信小编一定会给大家带来更优质的文章。谢谢大家对网站的支持!

0