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

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

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")
}

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:

确定