5

以io.Writer为例看go中的interface{}

 3 years ago
source link: http://blog.studygolang.com/2013/02/%e4%bb%a5io-writer%e4%b8%ba%e4%be%8b%e7%9c%8bgo%e4%b8%ad%e7%9a%84interface/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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接口:

1type Writer interface {
2Write(p []byte) (n int, err error)
3}

根据go中接口的特点,所有实现了Write方法的类型,我们都说它实现了io.Writer接口。

二、io.Writer的应用

通常,我们在使用fmt包的时候是使用Println/Printf/Print方法。其实,在fmt包中还有Fprint序列方法,而且,Print序列方法内部调用的是Fprint序列方法。以Fprintln为例看看方法的定义:

1func Fprintln(w io.Writer, a ...interface{}) (n int, err error)

方法的第一个参数是io.Writer,也就是说,任何实现了io.Writer接口的类型实例都可以传递进来;我们再看看Println方法内部实现:

1func Println(a ...interface{}) (n int, err error) {
2return Fprintln(os.Stdout, a...)
3}

我们不妨追溯一下os.Stdout:

1Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")

也就是标准输出。
从这里可以看出,os.File也实现了io.Writer,那么,如果第一个参数传递的是一个普通文件,内容便会被输出到该文件。
如果第一个参数传递的是bytes.Buffer,那么,内容便输出到了buffer中。

在写Web程序时,比如:

1func Index(rw http.ResponseWriter, req *http.Request) {
2fmt.Fprintln(rw, "Hello, World")
3}

这样便把”Hello World”输出给了客户端。

三、关于接口更多学习资料

1、Rob Pike谈Go中的接口

欢迎关注我的公众号:

polarisxu-qrcode-soso-s.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK