当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > Go语言interface详解

Go语言interface详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

interface

go语言里面设计最精妙的应该算interface,它让面向对象,内容组织实现非常的方便,当你看完这一章,你就会被interface的巧妙设计所折服。

什么是interface

简单的说,interface是一组method的组合,我们通过interface来定义对象的一组行为。

我们前面一章最后一个例子中student和employee都能sayhi,虽然他们的内部实现不一样,但是那不重要,重要的是他们都能say hi

让我们来继续做更多的扩展,student和employee实现另一个方法sing,然后student实现方法borrowmoney而employee实现spendsalary。

这样student实现了三个方法:sayhi、sing、borrowmoney;而employee实现了sayhi、sing、spendsalary。

上面这些方法的组合称为interface(被对象student和employee实现)。例如student和employee都实现了interface:sayhi和sing,也就是这两个对象是该interface类型。而employee没有实现这个interface:sayhi、sing和borrowmoney,因为employee没有实现borrowmoney这个方法。

interface类型

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

复制代码 代码如下:

type human struct {
    name string
    age int
    phone string
}

type student struct {
    human //匿名字段human
    school string
    loan float32
}

type employee struct {
    human //匿名字段human
    company string
    money float32
}

//human对象实现sayhi方法
func (h *human) sayhi() {
    fmt.printf("hi, i am %s you can call me on %s\n", h.name, h.phone)
}

// human对象实现sing方法
func (h *human) sing(lyrics string) {
    fmt.println("la la, la la la, la la la la la...", lyrics)
}

//human对象实现guzzle方法
func (h *human) guzzle(beerstein string) {
    fmt.println("guzzle guzzle guzzle...", beerstein)
}

// employee重载human的sayhi方法
func (e *employee) sayhi() {
    fmt.printf("hi, i am %s, i work at %s. call me on %s\n", e.name,
        e.company, e.phone) //此句可以分成多行
}

//student实现borrowmoney方法
func (s *student) borrowmoney(amount float32) {
    s.loan += amount // (again and again and...)
}

//employee实现spendsalary方法
func (e *employee) spendsalary(amount float32) {
    e.money -= amount // more vodka please!!! get me through the day!
}

// 定义interface
type men interface {
    sayhi()
    sing(lyrics string)
    guzzle(beerstein string)
}

type youngchap interface {
    sayhi()
    sing(song string)
    borrowmoney(amount float32)
}

type elderlygent interface {
    sayhi()
    sing(song string)
    spendsalary(amount float32)
}

通过上面的代码我们可以知道,interface可以被任意的对象实现。我们看到上面的men interface被human、student和employee实现。同理,一个对象可以实现任意多个interface,例如上面的student实现了men和youngchap两个interface。

最后,任意的类型都实现了空interface(我们这样定义:interface{}),也就是包含0个method的interface。

interface值

那么interface里面到底能存什么值呢?如果我们定义了一个interface的变量,那么这个变量里面可以存实现这个interface的任意类型的对象。例如上面例子中,我们定义了一个men interface类型的变量m,那么m里面可以存human、student或者employee值。

因为m能够持有这三种类型的对象,所以我们可以定义一个包含men类型元素的slice,这个slice可以被赋予实现了men接口的任意结构的对象,这个和我们传统意义上面的slice有所不同。

让我们来看一下下面这个例子:

复制代码 代码如下:

package main
import "fmt"

type human struct {
    name string
    age int
    phone string
}

type student struct {
    human //匿名字段
    school string
    loan float32
}

type employee struct {
    human //匿名字段
    company string
    money float32
}

//human实现sayhi方法
func (h human) sayhi() {
    fmt.printf("hi, i am %s you can call me on %s\n", h.name, h.phone)
}

//human实现sing方法
func (h human) sing(lyrics string) {
    fmt.println("la la la la...", lyrics)
}

//employee重载human的sayhi方法
func (e employee) sayhi() {
    fmt.printf("hi, i am %s, i work at %s. call me on %s\n", e.name,
        e.company, e.phone)
    }

// interface men被human,student和employee实现
// 因为这三个类型都实现了这两个方法
type men interface {
    sayhi()
    sing(lyrics string)
}

func main() {
    mike := student{human{"mike", 25, "222-222-xxx"}, "mit", 0.00}
    paul := student{human{"paul", 26, "111-222-xxx"}, "harvard", 100}
    sam := employee{human{"sam", 36, "444-222-xxx"}, "golang inc.", 1000}
    tom := employee{human{"tom", 37, "222-444-xxx"}, "things ltd.", 5000}

    //定义men类型的变量i
    var i men

    //i能存储student
    i = mike
    fmt.println("this is mike, a student:")
    i.sayhi()
    i.sing("november rain")

    //i也能存储employee
    i = tom
    fmt.println("this is tom, an employee:")
    i.sayhi()
    i.sing("born to be wild")

    //定义了slice men
    fmt.println("let's use a slice of men and see what happens")
    x := make([]men, 3)
    //这三个都是不同类型的元素,但是他们实现了interface同一个接口
    x[0], x[1], x[2] = paul, sam, mike

    for _, value := range x{
        value.sayhi()
    }
}

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

空interface

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

复制代码 代码如下:

// 定义a为空接口
var a interface{}
var i int = 5
s := "hello world"
// a可以存储任意类型的数值
a = i
a = s

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

interface函数参数

interface的变量可以持有任意实现该interface类型的对象,这给我们编写函数(包括method)提供了一些额外的思考,我们是不是可以通过定义interface参数,让函数接受各种类型的参数。

举个例子:fmt.println是我们常用的一个函数,但是你是否注意到它可以接受任意类型的数据。打开fmt的源码文件,你会看到这样一个定义:

复制代码 代码如下:

type stringer interface {
     string() string
}

也就是说,任何实现了string方法的类型都能作为参数被fmt.println调用,让我们来试一试
复制代码 代码如下:

package main
import (
    "fmt"
    "strconv"
)

type human struct {
    name string
    age int
    phone string
}

// 通过这个方法 human 实现了 fmt.stringer
func (h human) string() string {
    return "❰"+h.name+" - "+strconv.itoa(h.age)+" years -  ✆ " +h.phone+"❱"
}

func main() {
    bob := human{"bob", 39, "000-7777-xxx"}
    fmt.println("this human is : ", bob)
}

现在我们再回顾一下前面的box示例,你会发现color结构也定义了一个method:string。其实这也是实现了fmt.stringer这个interface,即如果需要某个类型能被fmt包以特殊的格式输出,你就必须实现stringer这个接口。如果没有实现这个接口,fmt将以默认的方式输出。

复制代码 代码如下:

//实现同样的功能
fmt.println("the biggest one is", boxes.biggestscolor().string())
fmt.println("the biggest one is", boxes.biggestscolor())

注:实现了error接口的对象(即实现了error() string的对象),使用fmt输出时,会调用error()方法,因此不必再定义string()方法了。

interface变量存储的类型

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

comma-ok断言

go语言里面有一个语法,可以直接判断是否是该类型的变量: value, ok = element.(t),这里value就是变量的值,ok是一个bool类型,element是interface变量,t是断言的类型。

如果element里面确实存储了t类型的数值,那么ok返回true,否则返回false。

让我们通过一个例子来更加深入的理解。

复制代码 代码如下:

package main

import (
    "fmt"
    "strconv"
)

type element interface{}
type list [] element

type person struct {
    name string
    age int
}

//定义了string方法,实现了fmt.stringer
func (p person) string() string {
    return "(name: " + p.name + " - age: "+strconv.itoa(p.age)+ " years)"
}

func main() {
    list := make(list, 3)
    list[0] = 1 // an int
    list[1] = "hello" // a string
    list[2] = person{"dennis", 70}

    for index, element := range list {
        if value, ok := element.(int); ok {
            fmt.printf("list[%d] is an int and its value is %d\n", index, value)
        } else if value, ok := element.(string); ok {
            fmt.printf("list[%d] is a string and its value is %s\n", index, value)
        } else if value, ok := element.(person); ok {
            fmt.printf("list[%d] is a person and its value is %s\n", index, value)
        } else {
            fmt.println("list[%d] is of a different type", index)
        }
    }
}

是不是很简单啊,同时你是否注意到了多个if里面,还记得我前面介绍流程时讲过,if里面允许初始化变量。

也许你注意到了,我们断言的类型越多,那么if else也就越多,所以才引出了下面要介绍的switch。

switch测试

最好的讲解就是代码例子,现在让我们重写上面的这个实现

复制代码 代码如下:

package main

import (
    "fmt"
    "strconv"
)

type element interface{}
type list [] element

type person struct {
    name string
    age int
}

//打印
func (p person) string() string {
    return "(name: " + p.name + " - age: "+strconv.itoa(p.age)+ " years)"
}

func main() {
    list := make(list, 3)
    list[0] = 1 //an int
    list[1] = "hello" //a string
    list[2] = person{"dennis", 70}

    for index, element := range list{
        switch value := element.(type) {
            case int:
                fmt.printf("list[%d] is an int and its value is %d\n", index, value)
            case string:
                fmt.printf("list[%d] is a string and its value is %s\n", index, value)
            case person:
                fmt.printf("list[%d] is a person and its value is %s\n", index, value)
            default:
                fmt.println("list[%d] is of a different type", index)
        }
    }
}

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

嵌入interface

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

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

复制代码 代码如下:

type interface interface {
    sort.interface //嵌入字段sort.interface
    push(x interface{}) //a push method to push elements into the heap
    pop() interface{} //a pop elements that pops elements from the heap
}

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

复制代码 代码如下:

type interface interface {
    // len is the number of elements in the collection.
    len() int
    // less returns 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)
}

另一个例子就是io包下面的 io.readwriter ,它包含了io包下面的reader和writer两个interface:

复制代码 代码如下:

// io.readwriter
type readwriter interface {
    reader
    writer
}

反射

go语言实现了反射,所谓反射就是能检查程序在运行时的状态。我们一般用到的包是reflect包。如何运用reflect包,官方的这篇文章详细的讲解了reflect包的实现原理,laws of reflection

使用reflect一般分成三步,下面简要的讲解一下:要去反射是一个类型的值(这些值都实现了空interface),首先需要把它转化成reflect对象(reflect.type或者reflect.value,根据不同的情况调用不同的函数)。这两种获取方式如下:

复制代码 代码如下:

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

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

tag := t.elem().field(0).tag  //获取定义在struct里面的标签
name := v.elem().field(0).string()  //获取存储在第一个字段里面的值

获取反射值能返回相应的类型和数值
复制代码 代码如下:

var x float64 = 3.4
v := reflect.valueof(x)
fmt.println("type:", v.type())
fmt.println("kind is float64:", v.kind() == reflect.float64)
fmt.println("value:", v.float())

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

复制代码 代码如下:

var x float64 = 3.4
v := reflect.valueof(x)
v.setfloat(7.1)

如果要修改相应的值,必须这样写
复制代码 代码如下:

var x float64 = 3.4
p := reflect.valueof(&x)
v := p.elem()
v.setfloat(7.1)

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网