24 December 2017

本文简单总结自Understanding Go Interfaces,对应的PPT

In object-oriented programming, a protocol or interface is a common means for unrelated objects to communicate with each other.

concrete types

  • 描述了内存布局

  • 通过方法将行为绑定到数据上
type Number int
func (n Number) Positive() bool {
    return n > 0

abstract types

  • 描述了行为

  • 定义了方法集
type Positiver interface {
    Positive() bool



// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
type Interface interface {
	// Len is the number of elements in the collection.
	Len() int
	// Less reports whether the element with
	// index i should sort before the element with index j.
	Less(i, j int) bool
	// Swap swaps the elements with indexes i and j.
	Swap(i, j int)



type headers struct {
    rt http.RoundTripper
    v map[string]string

func (h headers) RoundTrip(r *http.Request) (*http.Response, error) {
    for key, value := range h.v {
        r.Header.Set(key, value)
    return h.rt.RoundTrip(r)

func main() {
    c := &http.Client{
        Transport: headers{
            rt: http.DefaultTransport,
            v: map[string]string{"foo": "bar"},

    res, err := c.Get("http://golang.org")

The bigger the interface, the weaker the abstraction. - Rob Pike


Be conservative in what you do/send, be liberal in what you accept from others. - Robustness Principle


Return concrete types, receive interface as parameters.

Golang interface与其他语言的interface不同点主要在于Golang interface是隐式实现的,而其他语言需要显示的implement。