golang语言渐入佳境[19]-从go源代码读懂interface接口
2018-12-05 19:48
821 查看
go源代码中的接口
http库中,get方法:
1 | func Get(url string) (resp *Response, err error) |
Response:
12 | type Response struct { |
io.ReadCloser:
12 | type ReadCloser interface { Reader Closer } |
Reader:
12 | type Reader interface { Read(p []byte) (n int, err error) } |
Closer:
12 | type Closer interface { Close() error } |
不管是读取文件、网络等操作,都实现了相同的Reader接口。当传递[]byte进去,会将读取到的byte放置进去。成功会返回成功的个数。
12 | package main import ( "net/http" "fmt" "os" ) func main(){ resp,err := http.Get("http://tmall.com") if err !=nil{ fmt.Println("Error:",err) os.Exit(1) } //设置大一点,read方法不会自动的扩容。 bs:=make([]byte,99999) //read函数将读取到的数据放入到bs中。 resp.Body.Read(bs) fmt.Println(string(bs)) } |
write接口
12 | type Writer interface { Write(p []byte) (n int, err error) } |
io.opy
12 | package main import ( "net/http" "fmt" "os" "io" ) func main(){ resp,err := http.Get("http://tmall.com") if err !=nil{ fmt.Println("Error:",err) os.Exit(1) } //读取resp.Body中的信息,写到os.Stdout中。os.Stdout实现了write接口,resp.Body实现了read接口。 io.Copy(os.Stdout,resp.Body) } |
io.copy源码
12 | func Copy(dst Writer, src Reader) (written int64, err error) { |
自定义Writer函数
12 | package main import ( "net/http" "fmt" "os" "io" ) type logWriter struct{} func main(){ resp,err := http.Get("http://tmall.com") if err !=nil{ fmt.Println("Error:",err) os.Exit(1) } lw:= logWriter{} //读取resp.Body中的信息,写到os.Stdout中。os.Stdout实现了write接口,resp.Body实现了read接口。 io.Copy(lw,resp.Body) } func (logWriter) Write(bs []byte)(int,error){ fmt.Println(string(bs)) fmt.Println("Just wrote this many bytes",len(bs)) return len(bs),nil } |
本文链接: https://dreamerjonson.com/2018/11/27/golang-19-source-interface/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY 4.0 CN协议 许可协议。转载请注明出处!
相关文章推荐
- 神奇的GO语言:空接口(interface)
- 修改Go语言(golang)编译器源代码让它支持UTF-8 BOM
- go语言之行--接口(interface)、反射(reflect)详解
- 【GoLang笔记】浅析Go语言Interface类型的语法行为及用法
- Go语言接口interface
- go语言中的接口interface
- 算法代码实现之堆排序,Golang(Go语言)实现
- go语言学习笔记-接口学习
- Go 接口interface 的用法
- golang语言渐入佳境[22]-string检索类函数
- Go语言中cannot convert adminname (type interface {}) to type *: need type assertion的解决办法
- Go语言interface详解(转)
- golang实战使用gin+xorm搭建go语言web框架restgo详解3 系统常用配置参数
- golang实战使用gin+xorm搭建go语言web框架restgo详解9 session、日志、鉴权、验证码等
- 一个Go语言接口和多操作系统实现的简单例子
- Go语言之接口
- Go实战--golang中MongoDB(mgo) 插入interface
- 【GoLang】转载:我为什么放弃Go语言,哈哈
- Go语言的接口机理
- 【Go学习】浅析Go语言Interface类型的语法行为及用法