Type definitions
一个类型定义创建了一个新的、独立的类型,这一类型与相应的类型共享相同的底层类型,同时将这一新的类型绑定到了一个标识符上。
TypeDef = identifier Type .
新类型称为定义类型。它与任何其他类型(包括它创建时使用的类型)不同。
type (
Point struct{ x, y float64 } // Point 和 struct{ x, y float64 } 是不同的类型
polar Point // polar and Point 表示不同的类型
)
type TreeNode struct {
left, right *TreeNode
value *Comparable
}
type Block interface {
BlockSize() int
Encrypt(src, dst []byte)
Decrypt(src, dst []byte)
}
一个定义的类型可以绑定方法。这一新定义的类型不会继承绑定到给定类型的任何方法,但是接口类型或复合类型的元素的方法集保持不变:
// Mutex 是拥有两个方法( Lock 和 Unlock)的类型
type Mutex struct { /* Mutex 成员 */ }
func (m *Mutex) Lock() { /* Lock 实现 */ }
func (m *Mutex) Unlock() { /* Unlock 实现 */ }
// NewMutex 与 Mutex 有着相同的成员,但是不含上面的两个方法
type NewMutex Mutex
// PtrMutex 的底层类型 *Mutex 的方法集不变
// 但是 PtrMutex 的方法集为空
type PtrMutex *Mutex
// *PrintableMutex 的嵌入字段 Mutex 绑定了 Lock 和 Unlock 两个方法
type PrintableMutex struct {
Mutex
}
// MyBlock 是接口类型,其与 Block 拥有相同的方法要求
type MyBlock Block
类型定义可用于定义不同的布尔、数字或字符串类型,并为它们绑定方法:
type TimeZone int
const (
EST TimeZone = -(5 + iota)
CST
MST
PST
)
func (tz TimeZone) String() string {
return fmt.Sprintf("GMT%+dh", tz)
}
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。