Go語言基礎之interface的使用

字號+ 編輯: IT男在阿里 修訂: Snake 來源: 利志分享 2023-09-09 我要說兩句(0)

本文以代碼形式做案例,講述go語言當中interface的使用方法。

package main

import (
    "fmt"
)


//注意:1:interface 可以被任意对象实现,一个类型/对象也可以实现多个 interface,2:方法不能重载,如 eat() eat(s string) 不能同时存在  

//组合:将一个 interface1 嵌入到另一个 interface2 的声明中。其作用相当于把 interface1 的函数包含到 interface2 中,但是组合中不同有重复的方法。1.只要两个接口中的方法列表相同(与顺序无关),即为相同的接口,可以相互赋值。2. interface1 的方法列表属于另一个 interface2 的方法列表的子集,interface2 可以赋值给 interface1,反之不成立(因为方法缺失),interface2 中的方法会覆盖 interface1 中同名的方法。3.可以嵌入包中的 interface
  
type person struct {  
    name string  
    age  int  
}

func (p person) printMsg() {  
    fmt.Printf("I am %s, and my age is %d.\n", p.name, p.age)  
}

func (p person) eat(s string) {  
    fmt.Printf("%s is eating %s ...\n", p.name, s)  
}

func (p person) drink(s string) {  
    fmt.Printf("%s is drinking %s ...\n", p.name, s)  
}

type people interface {  
    printMsg()  
    peopleEat //组合  
    peopleDrink  
    //eat() //不能出现重复的方法  
}  

/**

type people interface {  
    printMsg()  
    eat()  
    drink()  
}
*/

type peopleDrink interface {  
    drink(s string)  
}

type peopleEat interface {  
    eat(s string)  
}

type peopleEatDrink interface {  
    eat(s string)  
    drink(s string)  
}



type foodie struct {  
    name string  
}

func (f foodie) eat(s string) {  
    fmt.Printf("I am foodie, %s. My favorite food is the %s.\n", f.name, s)  
}



func echoArray(a interface{}) {  
    b, _ := a.([]int) //这里是断言实现类型转换,如何不使用就会报错  
    for _, v := range b {  
        fmt.Println(v, " ")  
    }  
    return  
}


//要点:1interface关键字用来定义一个接口,2.Go没有implements、extends等关键字,3.实现一个接口的方法就是直接定义接口中的方法4.要实现多态,就要用指针或&object语法

func main() {  
    //定义一个people interface类型的变量p1
    var p1 people  
    p1 = person{"zhuihui", 40}  
    p1.printMsg()  
    p1.drink("orange juice")  

    //同一类可以属于多个 interface, 只要这个类实现了这个 interface中的方法
    var p2 peopleEat
    p2 = person{"zengzhihai", 40}
    p2.eat("bread")

    //不同类也可以实现同一个 interface
    var p3 peopleEat
    p3 = foodie{"ceshi"}
    p3.eat("noodle")

    //interface赋值
    p3 = p1 //p3中的方法会被p1中覆盖
    p3.eat("noodle")

    //interface查询
    //将子集peopleEat 转成people类型
    if p4, ok := p2.(people); ok {
        p4.drink("water")
        fmt.Println(p4)
    }

    //interface{}使得我们可以向函数传递任意类型的变量;
    //断言解决在使用interface{}的情况下,空接口类型向普通类型转换的类型转换问题;
    //普通类型之间的转换最好使用显式的类型转换,否者很可能导致严重的错误。
    a := []int{3, 5, 6}
    echoArray(a)

}


//可以作为任何形参和返回类型,mixed
閲完此文,您的感想如何?
  • 有用

    0

  • 沒用

    0

  • 開心

    0

  • 憤怒

    0

  • 可憐

    0

1.如文章侵犯了您的版權,請發郵件通知本站,該文章將在24小時内刪除;
2.本站標注原創的文章,轉發時煩請注明來源;
3.交流群: 2702237 13835667

相關課文
  • GO語言GORM如何更新字段

  • gorm如何創建記錄與模型定義需要注意什麽

  • gorm一般查詢與高級查詢

  • GORM時間戳跟蹤及CURD(增刪改查)

我要說說
網上賓友點評