通过嵌套结构体进行组合
在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()
}
结构体切片的嵌套
进一步处理,使用博客帖子的切片来创建一个网站。
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()
// output:
/*
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
*/
}
reference: