Go 并非彻底面向对象的编程语言。Go 官网的 FAQ 回答了 Go 是不是面向对象语言,摘录以下。程序员
能够说是,也能够说不是。虽然 Go 有类型和方法,支持面向对象的编程风格,但却没有类型的层次结构。Go 中的“接口”概念提供了一种不一样的方法,咱们认为它易于使用,也更为广泛。Go 也能够将结构体嵌套使用,这与子类化(Subclassing)相似,但并不彻底相同。此外,Go 提供的特性比 C++ 或 Java 更为通用:子类能够由任何类型的数据来定义,甚至是内建类型(如简单的“未装箱的”整型)。这在结构体(类)中没有受到限制。golang
Go 不支持类,而是提供告终构体。结构体中能够添加属性和方法。这样能够将数据和操做数据的方法绑定在一块儿,实现与类类似的效果。web
文件结构:编程
workspacepath -> oop -> employee -> employee.go 编程语言
workspacepath -> oop -> main.go函数
//employee.go文件
package employee import ( "fmt" ) type Employee struct { FirstName string LastName string TotalLeaves int LeavesTaken int } func (e Employee) LeavesRemaining() { fmt.Printf("%s %s has %d leaves remaining", e.FirstName, e.LastName, (e.TotalLeaves - e.LeavesTaken)) }
//main.go文件
package main import "oop/employee" func main() { e := employee.Employee { FirstName: "Sam", LastName: "Adolf", TotalLeaves: 30, LeavesTaken: 20, } e.LeavesRemaining() }
1.Go 并不支持构造器。若是某类型的零值不可用,须要程序员来隐藏该类型,避免从其余包直接访问。程序员应该提供一种名为 NewT(parameters)
的 函数,按照要求来初始化 T
类型的变量。 oop
2.应该让 Employee
结构体不可引用,修改 Employee为employee,这样别的文件就不能引用。
post
//employee.go文件
package employee import ( "fmt" ) type employee struct { firstName string lastName string totalLeaves int leavesTaken int } func New(firstName string, lastName string, totalLeave int, leavesTaken int) employee { e := employee {firstName, lastName, totalLeave, leavesTaken} return e } func (e employee) LeavesRemaining() { fmt.Printf("%s %s has %d leaves remaining", e.firstName, e.lastName, (e.totalLeaves - e.leavesTaken)) }
//main.go文件
package main import "oop/employee" func main() { e := employee.New("Sam", "Adolf", 30, 20) e.LeavesRemaining() }
总结:Go 不支持类,但结构体可以很好地取代类,而以 New(parameters)
签名的方法能够替代构造器。学习
Go 不支持继承,但它支持组合(Composition)。组合通常定义为“合并在一块儿”。汽车就是一个关于组合的例子:一辆汽车由车轮、引擎和其余各类部件组合在一块儿。网站
在 Go 中,经过在结构体内嵌套结构体,能够实现组合。
组合的典型例子就是博客帖子。每个博客的帖子都有标题、内容和做者信息。使用组合能够很好地表示它们。经过学习本教程后面的内容,咱们会知道如何实现组合。
package main import ( "fmt" ) type author struct { firstName string lastName string bio string } func (a author) fullName() string { return fmt.Sprintf("%s %s", a.firstName, a.lastName) } type post struct { title string content string author } func (p post) details() { fmt.Println("Title: ", p.title) fmt.Println("Content: ", p.content) fmt.Println("Author: ", p.fullName()) fmt.Println("Bio: ", p.bio) } func main() { author1 := author{ "Naveen", "Ramanathan", "Golang Enthusiast", } post1 := post{ "Inheritance in Go", "Go supports composition instead of inheritance", author1, } post1.details() }
Title: Inheritance in Go Content: Go supports composition instead of inheritance Author: Naveen Ramanathan Bio: Golang Enthusiast
package main import ( "fmt" ) type author struct { firstName string lastName string bio string } func (a author) fullName() string { return fmt.Sprintf("%s %s", a.firstName, a.lastName) } type post struct { title string content string author } func (p post) details() { fmt.Println("Title: ", p.title) fmt.Println("Content: ", p.content) fmt.Println("Author: ", p.fullName()) fmt.Println("Bio: ", p.bio) } type website struct { posts []post } func (w website) contents() { fmt.Println("Contents of Website\n") for _, v := range w.posts { v.details() fmt.Println() } } func main() { author1 := author{ "Naveen", "Ramanathan", "Golang Enthusiast", } post1 := post{ "Inheritance in Go", "Go supports composition instead of inheritance", author1, } post2 := post{ "Struct instead of Classes in Go", "Go does not support classes but methods can be added to structs", author1, } post3 := post{ "Concurrency", "Go is a concurrent language and not a parallel one", author1, } w := website{ posts: []post{post1, post2, post3}, } w.contents() }
在上面的主函数中,咱们建立了一个做者 author1
,以及三个帖子 post1
、post2
和 post3
。咱们最后经过嵌套三个帖子,在第 62 行建立了网站 w
,并在下一行显示内容。
程序会输出:
Contents of Website Title: Inheritance in Go Content: Go supports composition instead of inheritance Author: Naveen Ramanathan Bio: Golang Enthusiast Title: Struct instead of Classes in Go Content: Go does not support classes but methods can be added to structs Author: Naveen Ramanathan Bio: Golang Enthusiast Title: Concurrency Content: Go is a concurrent language and not a parallel one Author: Naveen Ramanathan Bio: Golang Enthusiast
Go 经过接口来实现多态。在 Go 语言中,咱们是隐式地实现接口。一个类型若是定义了接口所声明的所有方法,那它就实现了该接口。
一、多个类型能够实现同一个接口。
二、一个类型能够实现多个接口。
package main import ( "fmt" ) type Income interface { calculate() int source() string } type FixedBilling struct { projectName string biddedAmount int } type TimeAndMaterial struct { projectName string noOfHours int hourlyRate int } func (fb FixedBilling) calculate() int { return fb.biddedAmount } func (fb FixedBilling) source() string { return fb.projectName } func (tm TimeAndMaterial) calculate() int { return tm.noOfHours * tm.hourlyRate } func (tm TimeAndMaterial) source() string { return tm.projectName } func calculateNetIncome(ic []Income) { var netincome int = 0 for _, income := range ic { fmt.Printf("Income From %s = $%d\n", income.source(), income.calculate()) netincome += income.calculate() } fmt.Printf("Net income of organisation = $%d", netincome) } func main() { project1 := FixedBilling{projectName: "Project 1", biddedAmount: 5000} project2 := FixedBilling{projectName: "Project 2", biddedAmount: 10000} project3 := TimeAndMaterial{projectName: "Project 3", noOfHours: 160, hourlyRate: 25} incomeStreams := []Income{project1, project2, project3} calculateNetIncome(incomeStreams) }
在上面的 main
函数中,咱们建立了三个项目,有两个是 FixedBilling
类型,一个是 TimeAndMaterial
类型。接着咱们建立了一个 Income
类型的切片,存放了这三个项目。因为这三个项目都实现了 Interface
接口,所以能够把这三个项目放入 Income
切片。最后咱们将该切片做为参数,调用了 calculateNetIncome
函数,显示了项目不一样的收益和收入来源。
Income From Project 1 = $5000 Income From Project 2 = $10000 Income From Project 3 = $4000 Net income of organisation = $19000
refer:https://studygolang.com/articles/12681