面向对象
面向过程
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| package main
import "fmt"
func compare(a, b int) bool { return a < b } func main() { a, b := 1, 2 fmt.Println(compare(a, b)) }
true
|
类声明
面向对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| package main
import "fmt"
type Book struct { name string }
func (book Book) changName1(name string) string { book.name = name return book.name }
func (book *Book) changeName2(name string) string { book.name = name return book.name } func main() { b := Book{"时间简史"} fmt.Println(b.name) b.changName1("两只老虎爱跳舞") fmt.Println(b.name)
fmt.Println("====================") fmt.Println(b.name) b.changeName2("两只老虎爱跳舞") fmt.Println(b.name)
}
时间简史 时间简史 ==================== 时间简史 两只老虎爱跳舞
|
继承
确切的说 golang 中叫做组合(composition)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| package main
import ( "fmt" )
type Persons struct { Name string Age int }
func (p *Persons) getName() { fmt.Println("Name is ", p.Name) }
type Student struct { Persons Name string school string }
func main() {
s1 := &Student{} s1.Name = "john" s1.Persons.Name = "Persons Name" s1.Persons.Age = 24 s1.school = "QH" fmt.Println("s1 = ", s1)
s2 := &Student{ Persons: Persons{ Name: "Persons Name", Age: 24, }, Name: "john", school: "QH", } fmt.Println("s2 = ", s2) }
s1 = &{{Persons Name 24} john QH} s2 = &{{Persons Name 24} john QH}
|