This is a creation in Article, where the information may have evolved or changed. Welcome to the 27th chapter of [Golang Series Tutorial] (HTTPS://STUDYGOLANG.COM/SUBJECT/2). Go does not support inheritance, but it supports combinations (composition). Combinations are generally defined as "merged together." A car is an example of a combination: A car is made up of wheels, engines, and various other components. # # through nested structures in Go, by nesting structures within the structure, you can achieve the combination. A typical example of a portfolio is a blog post. Each blog post has title, content, and author information. Use a combination to represent them well. By following this tutorial, we will know how to implement a combination. We first create a ' author ' structure. "' Gopackage mainimport (" FMT ") type author struct {firstName string LastName string Bio String}func (a author) fullName ( ) string {return FMT. Sprintf ("%s%s", A.firstname, A.lastname)} ' in the code snippet above, we created a ' author ' struct, ' Author ' field has ' firstName ', ' lastName ' and ' bio '. We have also added a ' fullName () ' method, where ' author ' is the recipient type, and the method returns the author's full name. Next we create the ' post ' structure. ' Gotype 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.author.fullname ()) fmt. Println ("Bio:", P.author.bio)} ' post ' struct field has ' title ' and ' content '. It also has a nested anonymous field ' author '. This field specifies that ' author ' constitutes the ' post ' structure. Now ' post ' can access all fields of ' author ' structand methods. We also added the ' details () ' method to the ' post ' structure to print the title, the content, and the author's full name and profile. Once a struct field is nested within the structure, Go allows us to access its nested fields as if the fields belonged to the external structure. So the 11th line above ' p.author.fullname () ' can be replaced with ' p.fullname () '. The ' details () ' method can then be rewritten as follows: ' Gofunc (P post) details () {FMT. Println ("Title:", P.title) fmt. Println ("Content:", p.content) fmt. Println ("Author:", P.fullname ()) fmt. Println ("Bio:", P.bio)} ' Now that our ' author ' and ' Post ' structures are ready, let's create a blog post to complete this program. "' Gopackage mainimport (" 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{"in Heritance in Go "," go supports composition instead of inheritance ", Author1,} Post1.detaiLS ()} "[Run on Playground] (HTTPS://PLAY.GOLANG.ORG/P/SSKWATPJGR) in the above program, the main function creates a new ' author ' struct variable on line 31st. In line 36th, we create a ' post ' by nesting ' author1 '. The program output: "' Bashtitle:inheritance in Go Content:go supports composition instead of inheritance Author:naveen Ramanathan Bi O:golang Enthusiast ' # # structure Slice nesting we can further work with this example by using a slice of a blog post to create a Web site. :) We first define the ' website ' structure. In the main function of the code above, add the following code and run it. "' Gotype website struct {[]post}func (w website) contents () {FMT. Println ("Contents of website\n") for _, V: = Range w.posts {v.details () fmt. Println ()}} "" After you add the above code, when you run the program, the compiler will error, as follows: "' Bashmain.go:31:9: Syntax error:unexpected [, expecting field name or Embedded type ' ' error indicates a nested structure slice ' []post '. The reason for the error is that the struct cannot nest an anonymous slice. We need a field name. So let's fix this error and let the compiler pass. "' Gotype website struct {posts []post} ' can see that I have added a field name ']post ' to my post's slice ' [posts '. Now let's modify the main function to create some posts for our new site. The modified complete code looks like this: "' Gopackage mainimport (" FMT ") type author struct {firstName string LastName string Bio String}func (a auth OR) 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 D OES 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 ()}" [In PLAYG Run in round] (Https://play.golang.org/p/gKaa0RbeAE) in the main function above, we created an author ' Author1 ', and three posts ' post1 ', ' post2 ' and 'Post3 '. We finally created the site ' W ' in line 62nd by nesting three posts, and displayed the content on the next line. The program outputs: "' bashcontents of Websitetitle:inheritance in Go Content:go supports composition instead of inheritance author:n Aveen Ramanathan Bio:golang enthusiasttitle:struct instead of Classes in Go Content:go does not support Classes but met Hods can added to structs author:naveen Ramanathan Bio:golang enthusiasttitle:concurrency Content:go is a concurren T language and not a parallel one author:naveen Ramanathan bio:golang enthusiast ' ' This concludes this tutorial. Have a nice day. * * Previous tutorial-[struct substitution class] (https://studygolang.com/articles/12630) * * * * Next tutorial-[polymorphism] (https://studygolang.com/articles/12681) * *
Via:https://golangbot.com/inheritance
Author: Nick Coghlan Translator: Noluye proofreading: polaris1119
This article by GCTT original compilation, go language Chinese network honor launches
This article was originally translated by GCTT and the Go Language Chinese network. Also want to join the ranks of translators, for open source to do some of their own contribution? Welcome to join Gctt!
Translation work and translations are published only for the purpose of learning and communication, translation work in accordance with the provisions of the CC-BY-NC-SA agreement, if our work has violated your interests, please contact us promptly.
Welcome to the CC-BY-NC-SA agreement, please mark and keep the original/translation link and author/translator information in the text.
The article only represents the author's knowledge and views, if there are different points of view, please line up downstairs to spit groove
1772 reads