温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Go接口类型断言实例分析

发布时间:2022-01-11 14:42:09 来源:亿速云 阅读:132 作者:柒染 栏目:编程语言

小编今天带大家了解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 main



import (
	"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<len(studentarr);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<i;j++{

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

                a.Swap(j,j+1)

            }

        }

    }

}

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

go
AI