package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
resp, err := http.Get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502")
if err != nil {
panic(err)
}
defer resp.Body.Close()
bytes, _ := ioutil.ReadAll(resp.Body)
// ...
fmt.Printf("%sn",bytes)
}
- 这种写法也能实现读出网页的源码,但是这种方法耦合性太强
package infa
import (
"io/ioutil"
"net/http"
)
type Retriever struct {}
func(Retriever) Get(url string)string{
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
bytes, _ := ioutil.ReadAll(resp.Body)
return string(bytes)
}
Retriever
package testing
type Retriever struct {}
func (Retriever)Get(url string)string {
return "fake content"
}
downloader
package main
import (
"fmt"
infa "learngo/infra"
)
func getRetriever() infa.Retriever {
return infa.Retriever{}
}
func main() {
var retriever infa.Retriever = getRetriever()
bytes := retriever.Get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502")
// ...
fmt.Println(bytes)
}
- 这种相对于强耦合,耦合性降低了很多,但是retriever类型是有限制的,必须使用infa.Retriever;如果我们需要使用testing.Retriever的话代码就需要改动很大,改起来也会比较吃力
package main
import (
"fmt"
"learngo/testing"
)
func getRetriever() retriever {
return testing.Retriever{}
}
type retriever interface {
Get(string)string
}
func main() {
var retriever retriever = getRetriever()
bytes := retriever.Get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502")
// fake content
fmt.Println(bytes)
}
- 使用接口的话,我们使用Get方法需要使用infa.Retriever/testing.Retriever只需要改动getRetriever()函数内的返回值就可以了
大黄鸭是鸭子吗?
- 传统类型系统: 脊索动物门,脊椎动物亚门…(不是鸭子)
- duck typing:是鸭子;
duck typing
- 像鸭子走路,像鸭子叫(长得像鸭子),那么就是鸭子
- 描述事物的外部行为而非内部结构
- 严格来说go属于结构化类型系统,类似duck typing,但不是duck typing
def download(retriever):
return retriever.get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502")
- 运行时才知道传入的 retriever有没有get
- 通常需要注释来说明接口
templatestring download(const R& retriever){ return retriever.get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502") }
- 编译时才知道传入的retriever有没有get方法
- 通常需要注释来说明接口
String download(R r) { return r.get("https://blog.csdn.net/qq_43135259/article/details/123293118?spm=1001.2014.3001.5502") }
- 传入的参数必须实现Retriever接口
- 不是duck typing
- 由于强制性实现,不需要注释来说明接口
- 同时具有python,c++的duck typing的灵活性
- 又具有java的类型检查



