ch15、面向对象编程 - 行为的定义和实现
Is Go an object-oriented language?
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).
Also, the lack of a type hierarchy makes “objects” in Go feel much more lightweight than in languages such as C++ or Java.
Go语言的FQA页面:FQA - Is Go an object-oriented language?
1、封装数据和行为(方法)
Go语言封装数据:
/*
type Name struct {}
*/
package encapsulation
type Employee struct {
Id string
Name string
Age int
}
数据的初始化:
package encapsulation
import "testing"
type Employee struct {
Id string
Name string
Age int
}
func TestCreateEmployeeObj(t *testing.T) {
// 方法一
e := Employee{
"0", "Bob", 20}
// 方法二
e1 := Employee{
Name: "Mike", Age: 30}
// 方法三,使用new关键字(返回的是指针,使用.访问数据)
e2 := new(Employee) // 返回指针
e2.Id = "2"
e2.Name = "Rose"
e2.Age = 22
t.Log(e)
t.Log(e1)
t.Log(e1.Id)
t.Log(e2)
t.Logf("e is %T", e)
t.Logf("e2 is %T", e2)
}
封装行为(方法):
package error_test2
import (
"errors"
"testing"
)
func GetFibonacci(n int) ([]int, error) {
if n < 2 || n > 100 {
// 设置error返回10
return nil, errors.New("n's should be in [2,100]")
}
fibList := []int{
1, 1}
for i := 2; i < n; i++ {
fibList = append(fibList, fibList[i-2]+fibList