这是Go语言中组合的有效实现吗?

huangapple go评论105阅读模式
英文:

Is this a valid implementation of composition in Go?

问题

这是一个有效的组合吗?还是还有其他解决方案?

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type Person struct{ name string }
  7. type Swimmer struct{}
  8. func (s *Swimmer) Swim(name string) {
  9. fmt.Println(strings.Join([]string{
  10. name,
  11. " is swimming",
  12. }, ""))
  13. }
  14. type IronMan struct {
  15. person Person
  16. swimmer Swimmer
  17. }
  18. func (i *IronMan) Swim() {
  19. i.swimmer.Swim(i.person.name)
  20. }
  21. func main() {
  22. ironMan := IronMan{
  23. person: Person{"Mariottide"},
  24. swimmer: Swimmer{},
  25. }
  26. ironMan.Swim()
  27. }

这段代码是有效的。它定义了一个名为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?

  1. package main
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type Person struct{ name string }
  7. type Swimmer struct{}
  8. func (s *Swimmer) Swim(name string) {
  9. fmt.Println(strings.Join([]string{
  10. name,
  11. " is swimming",
  12. }, ""))
  13. }
  14. type IronMan struct {
  15. person Person
  16. swimmer Swimmer
  17. }
  18. func (i *IronMan) Swim() {
  19. i.swimmer.Swim(i.person.name)
  20. }
  21. func main() {
  22. ironMan := IronMan{
  23. person: Person{"Mariottide"},
  24. swimmer: Swimmer{},
  25. }
  26. ironMan.Swim()
  27. }

答案1

得分: 1

Go语言中有struct嵌入:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Person struct{ name string }
  6. func (p *Person) Talk(message string) {
  7. fmt.Printf("%s says: %s\n", p.name, message)
  8. }
  9. type Swimmer struct {
  10. Person
  11. }
  12. func (s *Swimmer) Swim() {
  13. fmt.Printf("%s is swimming\n", s.name)
  14. }
  15. type IronMan struct {
  16. Swimmer
  17. }
  18. func main() {
  19. ironMan := IronMan{Swimmer{Person{"Mariottide"}}}
  20. ironMan.Swim()
  21. ironMan.Talk("Hey")
  22. }
英文:

Go has struct embedding:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. type Person struct{ name string }
  6. func (p *Person) Talk(message string) {
  7. fmt.Printf("%s says: %s\n", p.name, message)
  8. }
  9. type Swimmer struct {
  10. Person
  11. }
  12. func (s *Swimmer) Swim() {
  13. fmt.Printf("%s is swimming\n", s.name)
  14. }
  15. type IronMan struct {
  16. Swimmer
  17. }
  18. func main() {
  19. ironMan := IronMan{Swimmer{Person{"Mariottide"}}}
  20. ironMan.Swim()
  21. ironMan.Talk("Hey")
  22. }

huangapple
  • 本文由 发表于 2017年9月17日 23:30:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/46265777.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定