golang接口

golang接口:实现多态

1.接口的定义(使用者)

package main

import (
    "fmt"
    "learngo/myinterface/mooc"
    "learngo/myinterface/real"
)

//實現者
type Retriever interface {
    Get(url string) string
}

//使用者
func download(r Retriever) string{
    return r.Get("http://www.imooc.com")
}

func main() {
    var r Retriever //Get方法的主人是誰
    r = mooc.Retriever{"asasass"}
    i := download(r)
    fmt.Println(i)

    fmt.Println("+++++++++++++++++++++++++++++++++++++")
    r = real.Retriever{}
    i = download(r)
    fmt.Println(i)

}
View Code

2.接口的实现者1

package mooc

type Retriever struct {
    Content string
}

func (r Retriever) Get(url string)  string{
    return r.Content
}
View Code

3.接口的实现者2

package real

import (
    "time"
    "net/http"
    "net/http/httputil"
)

type Retriever struct {
    Agent string
    Timeout time.Duration
}

func (r Retriever) Get(url string) string {
    resp, err := http.Get(url)
    defer resp.Body.Close()
    if err != nil {
        panic(err)
    }

    result, err := httputil.DumpResponse(resp, true)
    if err != nil {
        panic(err)
    }
    return string(result)
}
View Code
原文地址:https://www.cnblogs.com/xingyunshizhe/p/10775891.html