Golang语言中的interface是什么(下)

frankphper · 2019-05-06 19:22:39 · 815 次点击 · 预计阅读时间 3 分钟 · 大约8小时之前 开始浏览    
这是一个创建于 2019-05-06 19:22:39 的文章,其中的信息可能已经有所发展或是发生改变。

interface接口还可以作为函数参数,因为interface的变量可以持有任意实现该interface类型的对象,我们可以通过定义interface参数,让函数接受各种类型的参数。 判断interface变量存储的元素的类型,目前常用的有两种方法:Comma-ok断言和switch测试。

/**
 * interface接口作为函数参数
 * 判断interface变量存储的元素的类型
 */
package main

import (
    "fmt"
    "strconv"
)

// 定义Human对象
type Human struct {
    name  string
    age   int 
    phone string
}

// 定义空接口
type Element interface{}

// 定义切片
type List []Element

// 定义Person对象
type Person struct {
    name string
    age  int 
}

// 通过定义interface参数,让函数接受各种类型的参数
// 通过这个Method(方法),Human对象实现了fmt.Stringer接口
// Stringer接口是fmt.Println()的参数,最终使得Human对象可以作为fmt.Println的参数被调用
func (h Human) String() string {
    return "<" + h.name + " - " + strconv.Itoa(h.age) + " years - phone: " + h.phone + ">" 
}

// 通过定义interface参数,让函数接受各种类型的参数
// 通过这个Method(方法),Person对象实现了fmt.Stringer接口
// Stringer接口是fmt.Println()的参数,最终使得Person对象可以作为fmt.Println的参数被调用
func (p Person) String() string {
    return "(name: " + p.name + " - age: " + strconv.Itoa(p.age) + " years)"
}

func main() {
    // interface作为函数的参数传递
    Lucy := Human{"Lucy", 29, "10086"}
    fmt.Println("This human is:", Lucy)

    list := make(List, 3)
    list[0] = 100
    list[1] = "Hello Golang!"
    list[2] = Person{"Lily", 19}

    // Comma-ok断言
    for index, element := range list {
        // 判断变量的类型 格式:value, ok = element(T)
        // value是interface变量的值,ok是bool类型,element是interface的变量,T是断言的interface变量的类型
        if value, ok := element.(int); ok {
            fmt.Printf("list[%d] is an int and it's value is %d\n", index, value)
        } else if value, ok := element.(string); ok {
            fmt.Printf("list[%d] is a string and it's value is %s\n", index, value)
        } else if value, ok := element.(Person); ok {
            fmt.Printf("list[%d] is a Person and it's value is %s\n", index, value)
        } else {
            fmt.Printf("list[%d] is a different type\n", index)
        }
    }

    // switch
    for index, element := range list {
        // 注意:element.(type)语法不能在switch外的任何逻辑中使用
        switch value := element.(type) {
        case int:
            fmt.Printf("list[%d] is an int, it's value is %d\n", index, value)
        case string:
            fmt.Printf("list[%d] is a string, it's value is %s\n", index, value)
        case Person:
            fmt.Printf("list[%d] is a Person, it's value is %s\n", index, value)
        default:
            fmt.Printf("list[%d] is a differernt type", index)
        }
    }
}

有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

815 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传