go"繼承"

songtianyi發表於2017-02-17

這兩種方式有本質的區別麼?

package main

import (
    "fmt"
)

type Book struct {
    Title  string
    Author string
    Intor  string
}
type MyBook struct {
    Book
    Content string
}

func main() {
    my := &MyBook{
        Content: "xxx",
    }
    my.Book = Book{
        Title:  "Go",
        Author: "songtianyi",
        Intor:  "GoGoGo",
    }
    fmt.Println(my)
    fmt.Println(my.Title)
}
package main

import (
    "fmt"
)

type Book struct {
    Title  string
    Author string
    Intor  string
}
type MyBook struct {
    Bo      Book
    Content string
}

func main() {
    my := &MyBook{
        Content: "xxx",
    }
    my.Bo = Book{
        Title:  "Go",
        Author: "songtianyi",
        Intor:  "GoGoGo",
    }
    fmt.Println(my)
    fmt.Println(my.Bo.Title)
}

好像並沒有什麼區別, 唯一的區別是呼叫屬性和方法的時候 可以省去 Book

package main

import (
    "fmt"
)

type Book struct {
    Title  string
    Author string
    Intor  string
}

func (s *Book) String() {
    fmt.Println(s.Title, s.Author, s.Intor)
}

type MyBook struct {
    Book
    Content string
}

func main() {
    my := &MyBook{
        Content: "xxx",
    }
    my.Book = Book{
        Title:  "Go",
        Author: "songtianyi",
        Intor:  "GoGoGo",
    }
    fmt.Println(my)
    fmt.Println(my.Title)
    my.String()
}
更多原創文章乾貨分享,請關注公眾號
  • go"繼承"
  • 加微信實戰群請加微信(註明:實戰群):gocnio

相關文章