英文:
Is this a valid implementation of composition in Go?
问题
这是一个有效的组合吗?还是还有其他解决方案?
package main
import (
"fmt"
"strings"
)
type Person struct{ name string }
type Swimmer struct{}
func (s *Swimmer) Swim(name string) {
fmt.Println(strings.Join([]string{
name,
" is swimming",
}, ""))
}
type IronMan struct {
person Person
swimmer Swimmer
}
func (i *IronMan) Swim() {
i.swimmer.Swim(i.person.name)
}
func main() {
ironMan := IronMan{
person: Person{"Mariottide"},
swimmer: Swimmer{},
}
ironMan.Swim()
}
这段代码是有效的。它定义了一个名为Person
的结构体,一个名为Swimmer
的结构体,以及一个名为IronMan
的结构体。Swimmer
结构体有一个Swim
方法,用于打印出人名和" is swimming"的信息。IronMan
结构体包含一个Person
类型的字段和一个Swimmer
类型的字段。IronMan
结构体还有一个Swim
方法,它调用了Swimmer
结构体的Swim
方法,并传入了Person
结构体的name
字段作为参数。在main
函数中,创建了一个IronMan
实例,并调用了它的Swim
方法。运行代码将输出"Marriottide is swimming"。
英文:
Is this valid composition? Or there are other solutions?
package main
import (
"fmt"
"strings"
)
type Person struct{ name string }
type Swimmer struct{}
func (s *Swimmer) Swim(name string) {
fmt.Println(strings.Join([]string{
name,
" is swimming",
}, ""))
}
type IronMan struct {
person Person
swimmer Swimmer
}
func (i *IronMan) Swim() {
i.swimmer.Swim(i.person.name)
}
func main() {
ironMan := IronMan{
person: Person{"Mariottide"},
swimmer: Swimmer{},
}
ironMan.Swim()
}
答案1
得分: 1
Go语言中有struct
嵌入:
package main
import (
"fmt"
)
type Person struct{ name string }
func (p *Person) Talk(message string) {
fmt.Printf("%s says: %s\n", p.name, message)
}
type Swimmer struct {
Person
}
func (s *Swimmer) Swim() {
fmt.Printf("%s is swimming\n", s.name)
}
type IronMan struct {
Swimmer
}
func main() {
ironMan := IronMan{Swimmer{Person{"Mariottide"}}}
ironMan.Swim()
ironMan.Talk("Hey")
}
英文:
Go has struct
embedding:
package main
import (
"fmt"
)
type Person struct{ name string }
func (p *Person) Talk(message string) {
fmt.Printf("%s says: %s\n", p.name, message)
}
type Swimmer struct {
Person
}
func (s *Swimmer) Swim() {
fmt.Printf("%s is swimming\n", s.name)
}
type IronMan struct {
Swimmer
}
func main() {
ironMan := IronMan{Swimmer{Person{"Mariottide"}}}
ironMan.Swim()
ironMan.Talk("Hey")
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论