Title: Inheritance in Go Content: Go supports composition instead of inheritance Author: Naveen Ramanathan Bio: Golang Enthusiast
嵌入结构的片断
我们可以在这个例子的基础上更进一步,用博客文章的切片来创建一个网站:)。
我们先来定义website结构。请在现有程序的main函数上方添加以下代码并运行。
1 2 3 4 5 6 7 8 9 10
type website struct { []blogPost } func(w website) contents() { fmt.Println("Contents of Website\n") for _, v := range w.blogPosts { v.details() fmt.Println() } }
在添加上述代码后运行上述程序时,编译器会报如下错误:
1
main.go:31:9: syntax error: unexpected [, expecting field name or embedded type
func(w website) contents() { fmt.Println("Contents of Website\n") for _, v := range w.blogPosts { v.details() fmt.Println() } }
funcmain() { author1 := author{ "Naveen", "Ramanathan", "Golang Enthusiast", } blogPost1 := blogPost{ "Inheritance in Go", "Go supports composition instead of inheritance", author1, } blogPost2 := blogPost{ "Struct instead of Classes in Go", "Go does not support classes but methods can be added to structs", author1, } blogPost3 := blogPost{ "Concurrency", "Go is a concurrent language and not a parallel one", author1, } w := website{ blogPosts: []blogPost{blogPost1, blogPost2, blogPost3}, } w.contents() }
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