以io.Writer为例看go中的interface{}
Go’s interfaces—static, checked at compile time, dynamic when asked for—are, for me, the most exciting part of Go from a language design point of view. If I could export one feature of Go into other languages, it would be interfaces.
《Go Data Structures: Interfaces》—- Russ Cox
可见interface是go中很重要的一个特性。
在网上有人问:Go语言中接口到底有啥好处,能否举例说明?于是,我考虑以io.Writer接口为例谈谈interface{}
一、io.Writer接口
在go标准库io包中定义了Writer接口:
type Writer interface { Write(p []byte) (n int, err error) }
根据go中接口的特点,所有实现了Write方法的类型,我们都说它实现了io.Writer接口。
二、io.Writer的应用
通常,我们在使用fmt包的时候是使用Println/Printf/Print方法。其实,在fmt包中还有Fprint序列方法,而且,Print序列方法内部调用的是Fprint序列方法。以Fprintln为例看看方法的定义:
func Fprintln(w io.Writer, a ...interface{}) (n int, err error)
方法的第一个参数是io.Writer,也就是说,任何实现了io.Writer接口的类型实例都可以传递进来;我们再看看Println方法内部实现:
func Println(a ...interface{}) (n int, err error) { return Fprintln(os.Stdout, a...) }
我们不妨追溯一下os.Stdout:
Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
也就是标准输出。
从这里可以看出,os.File也实现了io.Writer,那么,如果第一个参数传递的是一个普通文件,内容便会被输出到该文件。
如果第一个参数传递的是bytes.Buffer,那么,内容便输出到了buffer中。
在写Web程序时,比如:
func Index(rw http.ResponseWriter, req *http.Request) { fmt.Fprintln(rw, "Hello, World") }
这样便把”Hello World”输出给了客户端。
三、关于接口更多学习资料
相关文章

11 thoughts on “以io.Writer为例看go中的interface{}”
一直搞不明白 io.reader 和 io.writer 怎么去理解。为什么要这么用?