这是有效的构图吗?还是有其他解决方案?

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

最佳答案

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 - 这是Go中组合的有效实现吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46265777/

10-10 15:51