这是有效的作文吗?还是有其他解决方案?
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()
}
答案 0 :(得分: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")
}