go"继承"

这两种方式有本质的区别么?


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()
}
已邀请:

gloomyzerg

赞同来自: songtianyi lvzhongyi Xanthus

你试着定义一个这样的接口例如


type BookInterface interface {
String()
}

然后这样


type Book struct {
Title string
Author string
Intor string
}

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

type MyBook1 struct {
bo Book
Content string
}

type MyBook2 struct {
Book
Content string
}

func main() {
my1 := &MyBook1{
Content: "xxx",
}
my1.bo = Book{
Title: "Go",
Author: "songtianyi",
Intor: "GoGoGo",
}

my2 := &MyBook2{
Content: "xxx",
}
my2.Book = Book{
Title: "Go",
Author: "songtianyi",
Intor: "GoGoGo",
}

fmt.Println(BookInterface(my1))
fmt.Println(BookInterface(my2))
}

你就会发现他们的区别

jmzwcn

赞同来自:

简洁就是美啊

jmzwcn

赞同来自:

*MyBook1 does not implement BookInterface (missing String method)

asdfsx

赞同来自:

本质区别就是第一个算是“继承”。第二个book只是mybook中的一个变量。

hooluupog

赞同来自:

你可以试着分别用Go和java实现一下intrusive List这个数据结构,就能切身体会到Go通过接口以及结构体嵌入来实现基于组合的思想和OOP里继承的不同之处。

lmw - hello world

赞同来自:

type MyBook struct {
Bo Book
Content string
}
本质是
type MyBook struct {
Bo Book
Content string
}
----------------------
type MyBook struct {
Book
Content string
}
本质是
type MyBook struct {
Title string
Author string
Intor string
Content string
}

要回复问题请先登录注册