Hands-On System Programming with Go
上QQ阅读APP看书,第一时间看更新

Custom-defined types

A package can define its own types by using the type defined definition expression, where definition is a type that shares a defined memory representation. Custom types can be defined by basic types:

type Message string    // custom string
type Counter int // custom integer
type Number float32 // custom float
type Success bool // custom boolean

They can also be defined by composite types like slices, maps, or pointers:

type StringDuo [2]string            // custom array   
type News chan string // custom channel
type Score map[string]int // custom map
type IntPtr *int // custom pointer
type Transform func(string) string // custom function
type Result struct { // custom struct
A, B int
}

They can also be used in combination with other custom types:

type Broadcast Message // custom Message
type Timer Counter // custom Counter
type News chan Message // custom channel of custom type Message

The main uses of custom types are to define methods and to make the type specific for a scope, like defining a string type called Message.

Interface definitions work in a different way. They can be defined by specifying a series of different methods, for instance:

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

They can also be a composition of other interfaces:

type ReadCloser interface {
Reader
Closer
}

Alternatively, they can be a combination of the two interfaces:

type ReadCloser interface {
Reader // composition
Close() error // method
}