定义
与传统的面向对象不同的是,go语言的接口是由使用者定义的
main
package main
import "fmt"
type Retriever interface {
Get(url string)string
}
func download(r Retriever)string{
return r.Get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502")
}
func main() {
var r Retriever
// runtime error: invalid memory address or nil pointer dereference
fmt.Println(download(r))
}
- 只有接口没有实现,去运行是会runtime error
实现
mockretriever
package mock
type Retriever struct {
Contents string
}
func (r Retriever)Get(url string)string{
return r.Contents
}
retriever
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)
}
main
package main
import (
"fmt"
"learngo/retriever/mock"
real2 "learngo/retriever/real"
)
type Retriever interface {
Get(url string) string
}
func download(r Retriever) string {
return r.Get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502")
}
func main() {
var r Retriever = mock.Retriever{"this is fake contents"}
// this is fake contents
fmt.Println(download(r))
r = real2.Retriever{}
// HTTP/2.0 200 OK ...
fmt.Println(download(r))
}
- go语言的实现都是隐式的,不像java一样需要implements
- 只要实现接口里的方法就可以了