1 of 9

Interface in Go

@English LT #3

25th Sep. 2017

1

The Go gopher was designed by Renée French.

The gopher stickers was made by Takuya Ueda.

Licensed under the Creative Commons 3.0 Attributions license.

2 of 9

Who am I?

Takuya Ueda

@tenntenn

2

Work for

Communities

&

Go Beginners

Go Conference

3 of 9

Interface in Go

Go’s interface has diffrent points with other languages.

  • Duck typing
  • Small interfaces

3

4 of 9

Type declaration

type <Identifier> <Type Literal>|<Named Type>

4

// Based on bult-in type

type Int int

// Based on other package type

type MyWriter io.Writer

// Based on type literal

type Person struct {

Name string

}

5 of 9

Method and Receiver

An user defined type can become a receiver’s type of a method.

5

type Hex int

func (h Hex) String() string {

return fmt.Sprintf("%x", int(h))

}

// Assigning 100 as Hex type

var hex Hex = 100

// Calling String method of Hex type

fmt.Println(hex.String())

6 of 9

Interface

Interface is a set of methods

  • implementing WITHOUTimplements” keyword
  • implemented means it have all listed methods

6

type Stringer interface {

String() string

}

// Hex implements Stringer interface

var s Stringer = Hex(100)

fmt.Println(s.String())

type Hex int

func (h Hex) String() string { ... }

7 of 9

Small interface

Keeping interface small is good design.

  • Easy to implement
  • High level abstraction
    • files, network connections, encoder, ...
  • Connecting io.Writer and io.Reader like Unix pipe

7

type Reader interface {

Read(p []byte) (n int, err error)

}

type Writer interface {

Write(p []byte) (n int, err error)

}

8 of 9

Conclutions

  • Interface is a set of methods
    • implementing without “implements“ keyword
    • You can implement an interface by only declaring all listed methods in the interface
  • Small interface is good design in Go
    • io.Reader and io.Writer is good example
    • Connecting small interfaces likes Unix pipe

8

9 of 9

9

Thank you!

twitter: @tenntenn

Qiita: tenntenn

connpass: tenntenn