版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chao2016/article/details/81557472
go语言的duck typing:
- 具有python,cpp的duck typing的灵活性
- 又具有java的类型检查
接口变量里有什么?
- 实现者的类型
- 实现者的值(或指针指向实现者)
注意:
- 接口变量里自带指针,接口变量本身采用值传递,几乎不需要使用接口的指针
- 指针接收者实现只能以指针方式使用;值接收者都可以
查看接口变量的两种方法:
- Type Assertion
- Type Switch
golang中表示任何类型:interface{}
1
1.1 retriever/mock/retriever.go:
package mock
import "fmt"
type Retriever struct {
Contents string
}
func (r *Retriever) String() string {
return fmt.Sprintf(
"Retriever: {Contents=%s}", r.Contents)
}
func (r *Retriever) Post(url string,
form map[string]string) string {
r.Contents = form["contents"]
return "ok"
}
func (r *Retriever) Get(url string) string {
return r.Contents
}
1.2 retriever/real/retriever.go:
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)
}
1.3 retriever/main.go:
package main
import (
"fmt"
"learngo/retriever/mock"
"learngo/retriever/real"
"time"
)
// 接口里面全是函数,不用加func关键字
type Retriever interface {
Get(url string) string
}
type Poster interface {
Post(url string,
form map[string]string) string
}
const url = "http://www.imooc.com"
func download(r Retriever) string {
return r.Get(url)
}
func post(poster Poster) {
poster.Post(url,
map[string]string{
"name": "ccmouse",
"course": "golang",
})
}
type RetrieverPoster interface {
Retriever
Poster
}
func session(s RetrieverPoster) string {
s.Post(url, map[string]string{
"contents": "another faked imooc.com",
})
return s.Get(url)
}
func main() {
var r Retriever
mockRetriever := mock.Retriever{
Contents: "this is a fake imooc.com"}
r = &mockRetriever
inspect(r)
r = &real.Retriever{
UserAgent: "Mozilla/5.0",
TimeOut: time.Minute,
}
inspect(r)
// Type assertion
if mockRetriever, ok := r.(*mock.Retriever); ok {
fmt.Println(mockRetriever.Contents)
} else {
fmt.Println("r is not a mock retriever")
}
fmt.Println(
"Try a session with mockRetriever")
fmt.Println(session(&mockRetriever))
}
func inspect(r Retriever) {
fmt.Println("Inspecting", r)
fmt.Printf(" > Type:%T Value:%v\n", r, r)
fmt.Print(" > Type switch: ")
switch v := r.(type) {
case *mock.Retriever:
fmt.Println("Contents:", v.Contents)
case *real.Retriever:
fmt.Println("UserAgent:", v.UserAgent)
}
fmt.Println()
}
1.4 Output:
Inspecting Retriever: {Contents=this is a fake imooc.com}
> Type:*mock.Retriever Value:Retriever: {Contents=this is a fake imooc.com}
> Type switch: Contents: this is a fake imooc.com
Inspecting &{Mozilla/5.0 1m0s}
> Type:*real.Retriever Value:&{Mozilla/5.0 1m0s}
> Type switch: UserAgent: Mozilla/5.0
r is not a mock retriever
Try a session with mockRetriever
another faked imooc.com
有疑问加站长微信联系(非本文作者)