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

以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”输出给了客户端。

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

1、Rob Pike谈Go中的接口

1 Star2 Stars3 Stars4 Stars5 Stars (3 人打了分, 平均分:4.00,总分:5)
Loading...

6 thoughts on “以io.Writer为例看go中的interface{}

    1. duck 模型
      只要实现了接口的方法就认为实现了接口,而不需要显示的指名一个类型实现某个接口。

      标准库很多地方用到 io.Writer 或 io.Reader,可以结合着理解。

  1. io.Writer 和os.Stdout之间的关系,这里可以说得更清楚些。
    标准库的os包(file.go):
    Stdout = NewFile(uintptr(syscall.Stdout), “/dev/stdout”)
    NewFile()返回的是*File:
    func NewFile(fd uintptr, name string) *File {}

    而*File也实现了Write方法:
    func (f *File) Write(b []byte) (n int, err error){}

  2. n most of these organs whereas breathing together with exhaling.It increases the blood circulation resulting from fresh availability of blood.It moreover improves the bowel movement which implies eliminating the general troublesome medical conditions.The abdominal muscle area will be toned by using the breathing technique.A feeling of calmness is achieved as a result of lightness of your skull.It allows you to think superior and have decisions quickly.It likewise keeps your brain alert.It will help clear your complete nervous model which proves that they are very useful to make your shape fit as well as fine.It’s a great breathing way to help your thoughts and soul.It helps awaken an individual’s spiritual vitality which rehabs many problems you keep facing the majority of the times.
    Caution:The reader with this article should exercise many precautions previously following the asanas made by this article along with the site.To prevent any challenges while carrying out the asanas, it’s advised which you consult medical help and a yoga tutor.The job lies solely with all the reader without with your website or any writer.moncler
    <a href

发表评论

电子邮件地址不会被公开。