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.
Who am I?
Takuya Ueda
@tenntenn
2
Work for
Communities
&
Go Beginners
Go Conference
Interface in Go
Go’s interface has diffrent points with other languages.
3
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
}
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())
Interface
Interface is a set of 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 { ... }
Small interface
Keeping interface small is good design.
7
type Reader interface {
Read(p []byte) (n int, err error)
}
type Writer interface {
Write(p []byte) (n int, err error)
}
Conclutions
8