【Duke】行为的定义和实现 013 - PingPongGooo/GoFoundation GitHub Wiki
Go与其他面向对象语言的区别 Go 官网这么写道 https://golang.org/doc/faq
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.
Also, the lack of a type hierarchy makes "objects" in Go feel much more lightweight than in languages such as C++ or Java.
也是也不是。go不支持继承。
封装数据和行为
对于数据的封装
type Employee struct{
Id string
Name string
Age int
}
实例创建及初始化
e := Employee{"0","Bob",20}
e1 := Employee{Name:"Mike", Age:30}
e2 := new(Employee) // 注意这里返回的引用/指针,相当于 e:= &Employee{}
e2.Id = "2"
e2.Age = 22
2.Name = "Rose"
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)
行为(方法)定义
与其他主要编程语言的差异
// 第一种定义方式在实例对应方法被调用时,实例的成员会进行值复制
func(e Employee)String()string{
return fmt.Sprintf("ID:%s-Name:%s-Age:%d",e.Id,e.Name,e.Age)
}
// 通常情况下为了避免内存拷贝我们使用第二种定义方式
func (e *Employee)String()string{
return fmt.Sprintf("ID:%s/Name:%s/Age:%d",e.Id,e.Name,e.Age)
}