• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

go语言学习日记三十三golanginterface

武飞扬头像
没枕头我咋睡觉
帮助1

什么是interface:

        interface是一组方法的组合。我们可以通过interface定义对象的一组行为。

interface类型:

        interface 类型定义了一组方法,如果某个对象实现了某个接口的所有方法,则此对象就实 现了此接口。详细的语法参考下面这个例子

  1.  
    type Human struct {
  2.  
    name string
  3.  
    age int
  4.  
    phone string
  5.  
    }
  6.  
     
  7.  
     
  8.  
    type Student struct {
  9.  
    Human //匿名字段 Human
  10.  
    school string
  11.  
    loan float32
  12.  
    }
  13.  
     
  14.  
     
  15.  
    type Employee struct {
  16.  
    Human //匿名字段 Human
  17.  
    company string
  18.  
    money float32
  19.  
    }
  20.  
     
  21.  
     
  22.  
    //Human 对象实现 Sayhi 方法
  23.  
    func (h *Human) SayHi() {
  24.  
    fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
  25.  
    }
  26.  
     
  27.  
     
  28.  
    // Human 对象实现 Sing 方法
  29.  
    func (h *Human) Sing(lyrics string) {
  30.  
    fmt.Println("La la, la la la, la la la la la...", lyrics)
  31.  
    }
  32.  
     
  33.  
     
  34.  
    //Human 对象实现 Guzzle 方法
  35.  
    func (h *Human) Guzzle(beerStein string) {
  36.  
    fmt.Println("Guzzle Guzzle Guzzle...", beerStein)
  37.  
    }
  38.  
     
  39.  
     
  40.  
    // Employee 重载 Human 的 Sayhi 方法
  41.  
    func (e *Employee) SayHi() {
  42.  
    fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
  43.  
    e.company, e.phone) //Yes you can split into 2 lines here.
  44.  
    }
  45.  
     
  46.  
     
  47.  
    //Student 实现 BorrowMoney 方法
  48.  
    func (s *Student) BorrowMoney(amount float32) {
  49.  
    s.loan = amount // (again and again and...)
  50.  
    }
  51.  
     
  52.  
     
  53.  
    //Employee 实现 SpendSalary 方法
  54.  
    func (e *Employee) SpendSalary(amount float32) {
  55.  
    e.money -= amount // More vodka please!!! Get me through the day!
  56.  
    }
  57.  
     
  58.  
     
  59.  
    // 定义 interface
  60.  
    type Men interface {
  61.  
    SayHi()
  62.  
    Sing(lyrics string)
  63.  
    Guzzle(beerStein string)
  64.  
    }
  65.  
     
  66.  
     
  67.  
     
  68.  
    type YoungChap interface {
  69.  
    SayHi()
  70.  
    Sing(song string)
  71.  
    BorrowMoney(amount float32)
  72.  
    }
  73.  
     
  74.  
     
  75.  
    type ElderlyGent interface {
  76.  
    SayHi()
  77.  
    Sing(song string)
  78.  
    SpendSalary(amount float32)
  79.  
    }
学新通

        通过上面的代码我们可以知道,interface 可以被任意的对象实现。我们看到上面的 Men interface 被 Human、Student 和 Employee 实现。同理,一个对象可以实现任意多个 interface,例如上面的 Student 实现了 Men 和 YonggChap 两个 interface。 最后,任意的类型都实现了空 interface(我们这样定义:interface{}),也就是包含 0 个 method 的 interface。     

interface值:

        如果我们定义了一个 interface 的变量,那么这个变量里面可以存实现这个 interface 的任意类型的对象。例如上面例子中,我们定义了一个 Men interface 类型的变量 m,那么 m 里面可以存 Human、Student 或者 Employee 值。 因为 m 能够持有这三种类型的对象,所以我们可以定义一个包含 Men 类型元素的 slice, 这个 slice 可以被赋予实现了 Men 接口的任意结构的对象,这个和我们传统意义上面的 slice 有所不同。

        举例:

  1.  
    package main
  2.  
     
  3.  
     
  4.  
    import "fmt"
  5.  
     
  6.  
     
  7.  
    type Human struct {
  8.  
    name string
  9.  
    age int
  10.  
    phone string
  11.  
    }
  12.  
     
  13.  
     
  14.  
    type Student struct {
  15.  
    Human //匿名字段
  16.  
    school string
  17.  
    loan float32
  18.  
    }
  19.  
     
  20.  
     
  21.  
    type Employee struct {
  22.  
    Human //匿名字段
  23.  
    company string
  24.  
    money float32
  25.  
    }
  26.  
     
  27.  
     
  28.  
    //Human 实现 Sayhi 方法
  29.  
    func (h Human) SayHi() {
  30.  
    fmt.Printf("Hi, I am %s you can call me on %s\n", h.name, h.phone)
  31.  
    }
  32.  
     
  33.  
     
  34.  
    //Human 实现 Sing 方法
  35.  
    func (h Human) Sing(lyrics string) {
  36.  
    fmt.Println("La la la la...", lyrics)
  37.  
    }
  38.  
     
  39.  
     
  40.  
    //Employee 重载 Human 的 SayHi 方法
  41.  
    func (e Employee) SayHi() {
  42.  
    fmt.Printf("Hi, I am %s, I work at %s. Call me on %s\n", e.name,
  43.  
    e.company, e.phone) //Yes you can split into 2 lines here.
  44.  
    }
  45.  
     
  46.  
     
  47.  
    // Interface Men 被 Human,Student 和 Employee 实现
  48.  
    // 因为这三个类型都实现了这两个方法
  49.  
    type Men interface {
  50.  
    SayHi()
  51.  
    Sing(lyrics string)
  52.  
    }
  53.  
     
  54.  
     
  55.  
    func main() {
  56.  
    mike := Student{Human{"Mike", 25, "222-222-XXX"}, "MIT", 0.00}
  57.  
    paul := Student{Human{"Paul", 26, "111-222-XXX"}, "Harvard", 100}
  58.  
    sam := Employee{Human{"Sam", 36, "444-222-XXX"}, "Golang Inc.", 1000}
  59.  
    Tom := Employee{Human{"Sam", 36, "444-222-XXX"}, "Things Ltd.", 5000}
  60.  
    //定义 Men 类型的变量 i
  61.  
    var i Men
  62.  
    //i 能存储 Student
  63.  
    i = mike
  64.  
    fmt.Println("This is Mike, a Student:")
  65.  
    i.SayHi()
  66.  
    i.Sing("November rain")
  67.  
    //i 也能存储 Employee
  68.  
    i = Tom
  69.  
    fmt.Println("This is Tom, an Employee:")
  70.  
    i.SayHi()
  71.  
    i.Sing("Born to be wild")
  72.  
    //定义了 slice Men
  73.  
    fmt.Println("Let's use a slice of Men and see what happens")
  74.  
    x := make([]Men, 3)
  75.  
    //T 这三个都是不同类型的元素,但是他们实现了 interface 同一个接口
  76.  
    x[0], x[1], x[2] = paul, sam, mike
  77.  
    for _, value := range x{
  78.  
    value.SayHi()
  79.  
    }
  80.  
    }
  81.  
     
  82.  
     
  83.  
     
学新通

        通过上面的代码,你会发现 interface 就是一组抽象方法的集合,它必须由其他非 interface 类型实现,而不能自我实现, go 通过 interface 实现了 duck-typing:即"当看到一只鸟走起 来像鸭子、游泳起来像鸭子、叫起来也像鸭子,那么这只鸟就可以被称为鸭子

空interface

        空 interface(interface{})不包含任何的 method,正因为如此,所有的类型都实现了空 interface。空 interface 对于描述起不到任何的作用(因为它不包含任何的 method),但是空 interface 在我们需要存储任意类型的数值的时候相当有用,因为它可以存储任意类型的数 值。它有点类似于 C 语言的 void*类型。

  1.  
    // 定义 a 为空接口
  2.  
    var a interface{}
  3.  
    var i int = 5
  4.  
    s := "Hello world"
  5.  
    // a 可以存储任意类型的数值
  6.  
    a = i
  7.  
    a = s

        一个函数把 interface{}作为参数,那么他可以接受任意类型的值作为参数,如果一个函数 返回 interface{},那么也就可以返回任意类型的值。是不是很有用啊!

interface 函数参数

         interface 的变量可以持有任意实现该 interface 类型的对象,这给我们编写函数(包括 method)提供了一些额外的思考,我们是不是可以通过定义 interface 参数,让函数接受各 种类型的参数。 举个例子:fmt.Println 是我们常用的一个函数,但是你是否注意到它可以接受任意类型的 数据。打开 fmt 的源码文件,你会看到这样一个定义:

  1.  
    type Stringer interface {
  2.  
    String() string
  3.  
    }

也就是说,任何实现了 String 方法的类型都能作为参数被 fmt.Println 调用,让我们来试一试

  1.  
    package main
  2.  
     
  3.  
     
  4.  
    import (
  5.  
    "fmt"
  6.  
    "strconv"
  7.  
    )
  8.  
     
  9.  
     
  10.  
    type Human struct {
  11.  
    name string
  12.  
    age int
  13.  
    phone string
  14.  
    }
  15.  
     
  16.  
     
  17.  
    // 通过这个方法 Human 实现了 fmt.Stringer
  18.  
    func (h Human) String() string {
  19.  
    return "❰" h.name " - " strconv.Itoa(h.age) " years - ✆ " h.phone "❱"
  20.  
    }
  21.  
     
  22.  
     
  23.  
    func main() {
  24.  
    Bob := Human{"Bob", 39, "000-7777-XXX"}
  25.  
    fmt.Println("This Human is : ", Bob)
  26.  
    }
  27.  
     
  28.  
     
  29.  
    /***************************************************************
  30.  
    This Human is : ❰Bob - 39 years - ✆ 000-7777-XXX❱
  31.  
    ***************************************************************/
学新通

interface 变量存储的类型

        我们知道 interface 的变量里面可以存储任意类型的数值(该类型实现了 interface)。那么我们 怎么反向知道这个变量里面实际保存了的是哪个类型的对象呢?目前常用的有两种方法:

         • Comma-ok 断言

                Go 语言里面有一个语法,可以直接判断是否是该类型的变量: value, ok = element.(T), 这里 value 就是变量的值,ok 是一个 bool 类型,element 是 interface 变量,T 是断言的类 型。 如果 element 里面确实存储了 T 类型的数值,那么 ok 返回 true,否则返回 false。 让我们通过一个例子来更加深入的理解。

  1.  
    package main
  2.  
     
  3.  
     
  4.  
    import (
  5.  
    "fmt"
  6.  
    "strconv"
  7.  
    )
  8.  
     
  9.  
     
  10.  
    type Element interface{}
  11.  
    type List [] Element
  12.  
    type Person struct {
  13.  
    name string
  14.  
    age int
  15.  
    }
  16.  
     
  17.  
     
  18.  
    //定义了 String 方法,实现了 fmt.Stringer
  19.  
    func (p Person) String() string {
  20.  
    return "(name: " p.name " - age: " strconv.Itoa(p.age) "years)"
  21.  
    }
  22.  
     
  23.  
     
  24.  
    func main() {
  25.  
    list := make(List, 3)
  26.  
    list[0] = 1 // an int
  27.  
    list[1] = "Hello" // a string
  28.  
    list[2] = Person{"Dennis", 70}
  29.  
    for index, element := range list {
  30.  
    if value, ok := element.(int); ok {
  31.  
    fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
  32.  
    } else if value, ok := element.(string); ok {
  33.  
    fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
  34.  
    } else if value, ok := element.(Person); ok {
  35.  
    fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
  36.  
    } else {
  37.  
    fmt.Println("list[%d] is of a different type", index)
  38.  
    }
  39.  
    }
  40.  
    }
学新通

        也许你注意到了,我们断言的类型越多,那么 ifelse 也就越多,所以才引出了下面要介绍 的 switch。我们重新上面的实现方式:

  1.  
    package main
  2.  
     
  3.  
     
  4.  
    import (
  5.  
    "fmt"
  6.  
    "strconv"
  7.  
    )
  8.  
     
  9.  
     
  10.  
    type Element interface{}
  11.  
    type List [] Element
  12.  
    type Person struct {
  13.  
    name string
  14.  
    age int
  15.  
    }
  16.  
     
  17.  
     
  18.  
    //打印
  19.  
    func (p Person) String() string {
  20.  
    return "(name: " p.name " - age: " strconv.Itoa(p.age) " years)"
  21.  
    }
  22.  
     
  23.  
     
  24.  
    func main() {
  25.  
    list := make(List, 3)
  26.  
    list[0] = 1 //an int
  27.  
    list[1] = "Hello" //a string
  28.  
    list[2] = Person{"Dennis", 70}
  29.  
    for index, element := range list{
  30.  
    switch value := element.(type) {
  31.  
    case int:
  32.  
    fmt.Printf("list[%d] is an int and its value is %d\n", index, value)
  33.  
    case string:
  34.  
    fmt.Printf("list[%d] is a string and its value is %s\n", index, value)
  35.  
    case Person:
  36.  
    fmt.Printf("list[%d] is a Person and its value is %s\n", index, value)
  37.  
    default:
  38.  
    fmt.Println("list[%d] is of a different type", index)
  39.  
    }
  40.  
    }
  41.  
    }
学新通

        这里有一点需要强调的是:element.(type)语法不能在 switch 外的任何逻辑里面使用,如 果你要在 switch 外面判断一个类型就使用 comma-ok

嵌入 interface

        Go 里面真正吸引人的是他内置的逻辑语法,就像我们在学习 Struct 时学习的匿名字段,多 么的优雅啊,那么相同的逻辑引入到 interface 里面,那不是更加完美了。如果一个 interface1 作为 interface2 的一个嵌入字段,那么 interface2 隐式的包含了 interface1 里面 的 method。

我们可以看到源码包 container/heap 里面有这样的一个定义

  1.  
    type Interface interface {
  2.  
    sort.Interface //嵌入字段 sort.Interface
  3.  
    Push(x interface{}) //a Push method to push elements into the
  4.  
    heap
  5.  
    Pop() interface{} //a Pop elements that pops elements from the
  6.  
    heap
  7.  
    }

        我们看到 sort.Interface 其实就是嵌入字段,把 sort.Interface 的所有 method 给隐式的包含 进来了。也就是下面三个方法

  1.  
    type Interface interface {
  2.  
    // Len is the number of elements in the collection.
  3.  
    Len() int
  4.  
    // Less returns whether the element with index i should sort
  5.  
    // before the element with index j.
  6.  
    Less(i, j int) bool
  7.  
    // Swap swaps the elements with indexes i and j.
  8.  
    Swap(i, j int)
  9.  
    }

反射

        Go 语言实现了反射,所谓反射就是动态运行时的状态。我们一般用到的包是 reflect 包。reflect 一般分成三步,下面简要的讲解一下:要去反射是一个类型的值(这些值都实现 了空 interface),首先需要把它转化成 reflect 对象(reflect.Type 或者 reflect.Value,根据不同的情况调用不同的函数)。这两种获取方式如下:

  1.  
    t := reflect.TypeOf(i) //得到类型的元数据,通过 t 我们能获取类型定义里面的所有元素
  2.  
    v := reflect.ValueOf(i) //得到实际的值,通过 v 我们获取存储在里面的值,还可以去改变值

转化为 reflect 对象之后我们就可以进行一些操作了,也就是将 reflect 对象转化成相应的值, 例如:

  1.  
    tag := t.Elem().Field(0).Tag //获取定义在 struct 里面的标签
  2.  
    name := v.Elem().Field(0).String() //获取存储在第一个字段里面的值

获取反射值能返回相应的类型和数值

  1.  
    var x float64 = 3.4
  2.  
    v := reflect.ValueOf(x)
  3.  
    fmt.Println("type:", v.Type())
  4.  
    fmt.Println("kind is float64:", v.Kind() == reflect.Float64)
  5.  
    fmt.Println("value:", v.Float())

        最后,反射的话,那么反射的字段必须是可修改的,我们前面学习过传值和传引用,这个 里面也是一样的道理,反射的字段必须是可读写的意思是,如果下面这样写,那么会发生错误

  1.  
    var x float64 = 3.4
  2.  
    v := reflect.ValueOf(x)
  3.  
    v.SetFloat(7.1)

如果要修改相应的值,必须这样写

  1.  
    var x float64 = 3.4
  2.  
    p := reflect.ValueOf(&x)
  3.  
    v := p.Elem()
  4.  
    v.SetFloat(7.1)

上面只是对反射的简单介绍,更深入的理解还需要自己在编程中不断的实践。

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgfhcgg
系列文章
更多 icon
同类精品
更多 icon
继续加载