Go语言的接口

一、接口的定义和好处

我们都知道接口给类提供了一种多态的机制,什么是多态,多态就是系统根据类型的具体实现完成不同的行为。

以下代码简单说明了接口的作用

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
)

// init 在main 函数之前调用
func init() {
    if len(os.Args) != 2 {
        fmt.Println("Usage: ./example2 <url>")
        os.Exit(-1)
    }
}

// main 是应用程序的入口
func main() {
    // 从Web 服务器得到响应
    r, err := http.Get(os.Args[1])
    if err != nil {
        fmt.Println(err)
        return
    }

    // 从Body 复制到Stdout
    io.Copy(os.Stdout, r.Body)
    if err := r.Body.Close(); err != nil {
        fmt.Println(err)
    }
}

①注意下 http.Get(os.Args[1]) 这里他的返回值r是一个Response对象的指针,也就是请求的结果

做过web开发的都知道,下面是源代码

func Get(url string) (resp *Response, err error) {
    return DefaultClient.Get(url)
}

以下是Response的结构,这里有一个Body,是一个io.ReadCloser类型的,这是啥?往下看

type Response struct {
    Status string // e.g. "200 OK"
    StatusCode int // e.g. 200
    Proto string // e.g. "HTTP/1.0"
    ProtoMajor int // e.g. 1
    ProtoMinor int // e.g. 0
    Header Header
    Body io.ReadCloser
    ContentLength int64
    TransferEncoding []string
    Close bool
    Uncompressed bool
    Trailer Header
    Request *Request
    TLS *tls.ConnectionState
}

ReadCloser是一个接口哦!Reader和Closer也同样是接口,接口里面都是方法。

type ReadCloser interface {
    Reader
    Closer
}

Reader接口

type Reader interface {
    Read(p []byte) (n int, err error)
}

Closer接口

type Closer interface {
    Close() error
}

②io.Copy(os.Stdout, r.Body) 这个方法,查看源码如下

func Copy(dst Writer, src Reader) (written int64, err error) {
    return copyBuffer(dst, src, nil)
}

这里的输入参数dst是一个实现了Writer接口的对象,而src则是一个实现了Reader接口的对象,由此,我们可以知道为什么io.Copy(os.Stdout, r.Body)的第二个参数可以传r.Body了,因为①中展示了Body这个对象是实现了Reader接口的。同理os.Stdout对象这个接口值表示标准输出设备,并且已经实现了io.Writer 接口

 

补充:http://www.flysnow.org/2017/05/08/go-in-action-go-reader-writer.html 这篇文章解释了stdout是怎么样继承了Reader和Writer接口的。

os.Stdout返回的是一个*File, File里面只有一个*file,而*file是实现了下面两个接口的,下面是Go的源码

func (f *File) Read(b []byte) (n int, err error) {
    if err := f.checkValid("read"); err != nil {
        return 0, err
    }
    n, e := f.read(b)
    return n, f.wrapErr("read", e)
}

func (f *File) Write(b []byte) (n int, err error) {
    if err := f.checkValid("write"); err != nil {
        return 0, err
    }
    n, e := f.write(b)
    if n < 0 {
        n = 0
    }
    if n != len(b) {
        err = io.ErrShortWrite
    }

    epipecheck(f, e)

    if e != nil {
        err = f.wrapErr("write", e)
    }

    return n, err
}

所以说*File本身是继承了Writer和Reader接口的类型。

 

综上有了参数或者返回值是接口类型,就不用关注于具体的返回类型是什么,只要实现了的接口的方法都是可以被接受的。

二、接口值和实际对象值是怎么转化和存储的

我们都知道 如果一个类型实现了某个接口,那么这个类型的实际值是可以赋值给一个接口的变量的。

在C#中是这样的,例如将一个List赋值给一个IEnumerable类型的变量

IEnumerable<int> list = new List<int>(); 

在Go语言中也是这样的,请看下面的代码

package main

import (
    "fmt"
)

type eat interface{
    eat()(string)
}

type Bird struct
{
    Name string 
}

func (bird Bird) eat()string{
    return "Bird:"+bird.Name+" eat"
}

func print(e eat){
    fmt.Println(e.eat())
}

// main 是应用程序的入口
func main() {

    bird1:= Bird{Name:"Big"}
    bird2:= new(Bird)
    bird2.Name = "Small"

    print(bird1)
    print(bird2)

    var eat1 eat
    eat1 = bird1
    print(eat1)
}

结果

Bird:Big eat

Bird:Small eat

Bird:Big eat

这里定义了一个eat接口,有一个Bird的类型实现了该接口,print函数接受一个eat接口类型的参数,

这里可以看到前两次直接把bird1和bird2作为参数传入到print函数内,第二次则是声明了一个eat接口类型的变量eat1,然后将bird1进行了赋值。换句话说接口类型变量实际承载了实际类型值。这里是如何承载的呢?

 

这里我们把 eat1 称作 接口值,将bird1称作实体类型值,eat1和bird1的关系如下:

接口值可以看成两部分组合(都是指针)而成的。第一部分是【iTable的地址】第二部分是【实体类型值的地址】

关于interface的解析:

https://www.cnblogs.com/qqmomery/p/6298771.html

 

三、方法集的概念

简单的讲:方法集定义了接口的接受规则

举例说明:

package main

import (
    "fmt"
)

type notifier interface {
    notify()
}

type user struct {
    name string
    email string
}

func (u user) notify() {
    fmt.Printf("Sending user email to %s<%s>\n",
        u.name,
        u.email)
}

func sendNotification(n notifier) {
    n.notify()
}

func main() {
    u := user{"Bill", "[email protected]"}
    sendNotification(u)

}

如上代码,定义了一个notifier接口,有一个方法nitify()方法,定义了一个user类型的结构,实现了notify方法,接收者类型是user,即实现了notifier接口,又定义了一个sendNotification方法,接收一个实现notifier接口的类型,并调用notify方法。

 

func (u *user) notify() {
    fmt.Printf("Sending user email to %s<%s>\n",
        u.name,
        u.email)
}

func main() {
    u := user{"Bill", "[email protected]"}
    sendNotification(u)
}

现在修正一下代码,将接收者改为user的指针类型。此时会发现原来调用的地方会出现错误。

 

cannot use u (type user) as type notifier in argument to sendNotification:user does not implement notifier (notify method has pointer receiver)

  

不能将u(类型是user)作为sendNotification 的参数类型notifier:user 类型并没有实现notifier(notify 方法使用指针接收者声明)

 

为什么会出现上面的问题?要了解用指针接收者来实现接口时为什么user 类型的值无法实现该接口,需要先了解方法集。方法集定义了一组关联到给定类型的值或者指针的方法。

定义方法时使用的接收者的类型决定了这个方法是关联到值,还是关联到指针,还是两个都关联。

补充资料:

https://studygolang.com/articles/9681

https://www.kancloud.cn/liupengjie/go/570054

以下是Go语言规范中的方法集:

上表的意思是:类型的值只能实现值接收者的接口;指向类型的指针,既可以实现值接收者的接口,也可以实现指针接收者的接口。

 

从接收者的角度来看一下这些规则

 

如果是值接收者,实体类型的值和指针都可以实现对应的接口;如果是指针接收者,那么只有类型的指针能够实现对应的接口。

所以针对上面的问题,将传入的u变成传入地址就可以了(可以套用一下表格,接收者*user对应的values是*user,所以传地址对应上面表格浅蓝色部分)

func (u *user) notify() {

    fmt.Printf("Sending user email to %s<%s>\n",

        u.name,

        u.email)

}

func main() {

    u := user{"Bill", "[email protected]"}

    sendNotification(&u)

}

综上我们总结一下,也就是说如果你的方法的接受者的类型是指针类型,那么方法的实现者就只能是指向该类型的指针类型,如果方法的接收者是值类型,那么方法的实现者可以是值类型也可以是指向该类型的指针类型。

 

面试题一个,下面的代码能否编译通过?

package main
import (
    "fmt"
)
type People interface {
    Speak(string) string
}
type Stduent struct{}
func (stu *Stduent) Speak(think string) (talk string) {
    if think == "bitch" {
        talk = "You are a good boy"
    } else {
        talk = "hi"
    }
    return
}
func main() {
    var peo People = Stduent{}
    think := "bitch"
    fmt.Println(peo.Speak(think))
}

答案:不能。

分析:首先Speak的方法的接收者是*Student , 根据上面的规则,那么实现该方法的实现者只能是 *Student,但是 var peo People = Student{} 这里却将Student作为实现者赋值给了接口,这里就会出现问题。

 

补充:书上解释这个规则,为什么会有这种限制的原因,说的是golang不是总能找到值的地址,这个地方不是很明白,可以参考下面的资料进行分析https://segmentfault.com/q/1010000015316158

简单解释:就是因为 Integer(25).pretty() 将被优化成一个整数(常量)25 调用 pretty 函数 。

 

里面涉及到了一个 可寻址对象的问题,可以参考下面的连接

https://colobu.com/2018/02/27/go-addressable/

下面的连接,说明了为什么Integer(25) 将被优化成一个整数(常量)25 

Because literal values are constants in Go, they only exist at compile time and don’t have an address.

https://www.ardanlabs.com/blog/2017/07/interface-semantics.html

https://segmentfault.com/a/1190000002687627 字面量的定义

Integer(25) 是一个字面量,而字面量是一个常量,所以没有办法寻址

四、多态

// Sample program to show how polymorphic behavior with interfaces.
package main

import (
    "fmt"
)

type notifier interface {
    notify()
}

// user defines a user in the program.
type user struct {
    name string
    email string
}

func (u *user) notify() {
    fmt.Printf("Sending user email to %s<%s>\n",
        u.name,
        u.email)
}

type admin struct {
    name string
    email string
}

func (a *admin) notify() {
    fmt.Printf("Sending admin email to %s<%s>\n",
        a.name,
        a.email)
}

// main is the entry point for the application.
func main() {
    // Create a user value and pass it to sendNotification.
    bill := user{"Bill", "[email protected]"}
    sendNotification(&bill)

    // Create an admin value and pass it to sendNotification.
    lisa := admin{"Lisa", "[email protected]"}
    sendNotification(&lisa)
}

func sendNotification(n notifier) {
    n.notify()
}

上面的代码很好的说明的接口的多态,user和admin都实现了notify方法,既实现了的notifier接口,sendNotification函数接收一个实现notifier接口的实例,从而user和admin都可以当作参数使用sendNotification函数,而sendNotification里面的notify方法执行根据的是具体传入的实例中实现的方法。

 

 

猜你喜欢

转载自www.cnblogs.com/dcz2015/p/10103353.html