继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Go(6 [接口 类型断言])

holdtom
关注TA
已关注
手记 1703
粉丝 240
获赞 991


Go接口 Interface

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

代码:

interface关键字

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

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

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)

    }

栗子:

使用接口的方法实现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)

            }

        }

    }

}

©著作权归作者所有:来自51CTO博客作者zhaichaoqun的原创作品,如需转载,请注明出处,否则将追究法律责任


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP