two/more different sets of data which each data requires it is own struct for different functions, and these two/more sets of data struct share the same field. how can I combine these two set of data (different types), and can be called by another function which requires access filed from each sets of data.
package main
import "fmt"
type Plants struct {
Name string
Age int
}
type Animal struct {
Name string
Age int
}
type General struct {
Name string
Age int
}
func (a *Animal) AnimalHealth() {
fmt.Printf("Animal: %s is %+v years old who is in healthy condition!
", a.Name, a.Age)
}
func (p *Plants) PlantsHealth() {
fmt.Printf("Plants: %s is %+v years old who is in healthy condition!
", p.Name, p.Age)
}
func (g *General) alive() {
fmt.Printf("%s is %+v alive.
", g.Name, g.Age)
}
func main() {
dog := Animal{
Name: "luckdog",
Age: 6,
}
flower := Plants{
Name: "sunflower",
Age: 5,
}
dog.AnimalHealth() // Output is required.
flower.PlantsHealth() // Output is required.
var all []interface{}
all = append(all, dog, flower)
fmt.Printf("Print out all %s
", all)
for _, v := range all {
fmt.Printf("This is iterate through all value %v
", v) //Tested *Animal data and *Plants data are combined.
// v.alive() // *** Output is required, how should access fields, brain is burning. ***
}
}
make v.alive() works.
Looks like you need a common interface:
type Animal interface {
DoSomething()
}
type A struct {
}
type B struct {
}
func (a *A) DoSomething() {
fmt.Println("A")
}
func (b *B) DoSomething() {
fmt.Println("B")
}
func test(some Animal) {
some.DoSomething()
}
func main() {
a := &A{}
b := &B{}
var all []interface{}
all = append(all, a, b)
for _, v := range all {
v.(Animal).DoSomething()
}
}
Update:
As have said @mkopriva, if you need to have common fields in both struct
you can create a new struct
and embed it in others:
type Animal interface {
DoSomething()
}
type Common struct {
Name string
}
type A struct {
Common
}
type B struct {
Common
}
func (a *Common ) DoSomething() {
fmt.Println(a.Name)
}
func test(some Animal) {
some.DoSomething()
}
func main() {
a := &A{Common{Name: "a"}}
b := &B{Common{Name: "b"}}
var all []interface{}
all = append(all, a, b)
for _, v := range all {
v.(Animal).DoSomething()
}
}