Golang不是一个纯面向对象的语言,摘自Golang [FAQ](This excerpt taken from Go's FAQs answers the question of whether Go is Object Oriented.) ,解释了golang是否为面向对象的语言。
Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general. There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Moreover, methods in Go are more general than in C++ or Java: they can be defined for any sort of data, even built-in types such as plain, “unboxed” integers. They are not restricted to structs (classes).
// Define the struct with all fields exportedtypeemployeestruct { firstName, lastName string totalLeaves, leavesTaken int}// Exported method with a receiver of Employeefunc (e employee) LeavesRemaining() { fmt.Printf("%s%s has %d leaves remaining.\n", e.firstName, e.lastName, (e.totalLeaves - e.leavesTaken))}// New function as a ConstructorfuncNew(firstName, lastName string, totalLeaves, leavesTaken int) employee { e := employee {firstName, lastName, totalLeaves, leavesTaken}return e}// Property of employeefunc (e employee) GetFirstName() string {return e.firstName}func (e employee) GetLastName() string {return e.lastName}func (e employee) GetTotal() int {return e.totalLeaves}
// author of the posttypeauthorstruct { firstName, lastName string bio string}// get the author full namefunc (a author) AuthorName() string {return fmt.Sprintf("%s%s", a.firstName, a.lastName)}// struct of post, `author` field promoted// so Post type can use `AuthorName` directlytypePoststruct { Title string Content stringauthor}func (p Post) Detail() { fmt.Println("Post:", p.Title) fmt.Println("Content:", p.Content) fmt.Println("Author:", p.AuthorName()) fmt.Println("Bio", p.bio)}
// post/website.gopackagepostimport"fmt"// define the websites struct which contains poststypeWebSitestruct { Posts []Post}// display the website msssagefunc (w WebSite) Display() { fmt.Println("The content of the website:\n")for _, po :=range w.Posts { po.Detail() fmt.Println() }}
// post/post.gopackagepost/* define the post struct */import ("fmt")// author of the posttypeauthorstruct { firstName, lastName string bio string}// get the author full namefunc (a author) AuthorName() string {return fmt.Sprintf("%s%s", a.firstName, a.lastName)}funcNewauthor(firstName, lastName, bio string) author {returnauthor{firstName, lastName, bio}}// struct of post, `author` field promoted// so Post type can use `AuthorName` directlytypePoststruct { Title string Content stringauthor}funcNewPost(title, content string, a author) Post {returnPost{title, content, a}}func (p Post) Detail() { fmt.Println("Post:", p.Title) fmt.Println("Content:", p.Content) fmt.Println("Author:", p.AuthorName()) fmt.Println("Bio:", p.bio)}