Object-oriented Programming
1. Go不是纯面向对象的语言
Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Moreover, methods in Go are more general than in C++ or Java: they can be defined for any sort of data, even built-in types such as plain, “unboxed” integers. They are not restricted to structs (classes).// Define the struct with all fields exported
type employee struct {
firstName, lastName string
totalLeaves, leavesTaken int
}
// Exported method with a receiver of Employee
func (e employee) LeavesRemaining() {
fmt.Printf("%s %s has %d leaves remaining.\n",
e.firstName, e.lastName, (e.totalLeaves - e.leavesTaken))
}
// New function as a Constructor
func New(firstName, lastName string, totalLeaves, leavesTaken int) employee {
e := employee {firstName, lastName, totalLeaves, leavesTaken}
return e
}
// Property of employee
func (e employee) GetFirstName() string {
return e.firstName
}
func (e employee) GetLastName() string {
return e.lastName
}
func (e employee) GetTotal() int {
return e.totalLeaves
}2. 使用组合代替继承
2.1 结构体的嵌套
2.2 嵌套的切片类型
2.3 在其他包使用
3. 多态 Polymorphism
Last updated