1、指针的定义和使用

go函数为传值(copy)

指针的定义

package real

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

type Retriever struct {
    UserAgent string
    TimeOut time.Duration
}

func (r *Retriever) Get(url string) string{
    resp,err := http.Get(url)
    if err !=nil {
        panic(err)
    }
    result,err := httputil.DumpResponse(resp,true)
    resp.Body.Close()
    if err != nil {
        panic(err)
    }
    return string(result)
}

指针的使用

package main

import (
    "fmt"
    "gomodtest/retriever/mock"
    "gomodtest/retriever/real"
    "time"
)

type Retriever interface {
    Get(url string) string
}

func download(r Retriever) string {
    return r.Get("https://www.imooc.com")
}

func main() {
    var r Retriever
    r = mock.Retriever{"this is a fake imooc.com"}
    fmt.Printf("%T %v\n",r,r)
    r = &real.Retriever{
        UserAgent:"Mozill/5.0",
        TimeOut:time.Minute,
    }
    fmt.Printf("%T %v\n",r,r)
    fmt.Println(download(r))
}





2、接口的定义及使用

在使用时定义接口的能力

接口的定义

package mock


type Retriever struct {
    Contents string
}

func (r Retriever) Get(url string) string {
    return r.Contents
}

接口的使用

package main

import (
    "fmt"
    "gomodtest/retriever/mock"
    "gomodtest/retriever/real"
    "time"
)

type Retriever interface {
    Get(url string) string
}

func download(r Retriever) string {
    return r.Get("https://www.imooc.com")
}

func main() {
    r := mock.Retriever{"this is a fake imooc.com"}
    fmt.Printf("%T %v\n",r,r)
    fmt.Println(download(r))
}

接口的组合

type Retriever interface {
    Get(url string) string
}
type Poster interface {
    Post(url string,form map[string]string) string
}
type RetrieverPoster interface {
    Retriever
    Poster
}
Scroll to Top