码迷,mamicode.com
首页 > 其他好文 > 详细

A Tour of Go Interfaces are satisfied implicitly

时间:2014-10-28 21:29:07      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   os   ar   sp   div   

A type implements an interface by implementing the methods.

There is no explicit declaration of intent.

Implicit interfaces decouple implementation packages from the packages that define the interfaces: neither depends on the other.

It also encourages the definition of precise interfaces, because you don‘t have to find every implementation and tag it with the new interface name.

Package io defines Reader and Writer; you don‘t have to.

package main

import (
    "fmt"
    "os"
)

type Reader interface {
    Read(b []byte) (n int, err error)
}
type Writer interface {
    Write(b []byte) (n int,err error)
}

type ReadWriter interface {
    Reader
    Writer
}

func main() {
    var w Writer
    
    //os.Stdout implements Writer
    w = os.Stdout

    fmt.Fprintf(w, "hello, writer\n")
}

 

A Tour of Go Interfaces are satisfied implicitly

标签:style   blog   http   io   color   os   ar   sp   div   

原文地址:http://www.cnblogs.com/ghgyj/p/4057705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!