首页 > 其他 > 详细

A Tour of Go Interfaces are satisfied implicitly

时间:2014-10-28 21:26:00      阅读:275      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!