接口由使用者定义
package main
import (
"fmt"
ioutil "io/ioutil"
"net/http"
)
func retrieve(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)
}
func main() {
//读取网页的源代码,这一部分放到了上面的函数中,主函数更加简洁客观
//resp, err := http.Get("http://www.imooc.com")
//if err != nil {
// panic(err)
//}
//defer resp.Body.Close()
//bytes,_:=ioutil.ReadAll(resp.Body)
fmt.Println(retrieve("https://www.imooc.com"))
}
实现把网页代码抓取下来
main函数
package main
import (
"GoWork/infra"
"fmt"
)
func gerRetriever() infra.Retriever{
return infra.Retriever{}
}
func main() {
//retriever:=infra.Retriever{}
//retriever:=gerRetriever() 分析类型
var retriever infra.Retriever=gerRetriever()
fmt.Println(retriever.Get("https://www.imooc.com")) //一定一定注意大小写!!!!!!!!!!
}
infra函数
package infra
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)
}
1
有两个代码,返回fake content,一个能打印网页的源代码
通过接口,可以实现两个调用
主函数
package main
import (
"GoWork/testing"
"fmt"
)
func gerRetriever() retriever{
return testing.Retriever{}
}
type retriever interface {
Get(url string)string
}
func main() {
//retriever:=infra.Retriever{}
//retriever:=gerRetriever() 分析类型
var r retriever=gerRetriever()
fmt.Println(r.Get("https://www.imooc.com")) //一定一定注意大小写!!!!!!!!!!
}
打印
package infra
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)
}
fake
package testing
type Retriever struct {
}
func (Retriever)Get(url string) string {
return "fake content"
}
func main() {
}
空接口是一个类型,可以接收任何类型的值
如果我们不确定要输入的类型是什么时,可以把函数的类型设为接口 interface{}来接收不同类型的值
func show(a interface{}){
}
func main(){
show(20)
show(true)
silce:=[]int{1,76,8}
show(silce)
}