-2

Let's supposed I've got the following interface and two structs that implement it:

type Tmp interface {
    MyTmp() string
}

type MyStructA struct {
    ArrayOfItems   []int
}

func (a MyStructA) MyTmp() string {
    return "Hello World"
}

type MyStructB struct {
    ArrayOfItems   []int
}

func (a MyStructB) MyTmp() string {
    return "Hello World B"
}

As you notice both MyStructA and MyStructB implement Tmp and both have a property named ArrayOfItems. Using the interface signature, how could I iterate over that property which both have? Something similar to:

func (c ADifferentStruct) iterate(myTmp Tmp) {

   for _, number := range myTmp.ArrayOfItems {
      fmt.Println(number)
   }
}

NOTE: I don't want to add another method to the interface (ie getter/setters) to process or to define ArrayOfItems

is this possible?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
HerbertRedford
  • 230
  • 4
  • 14

1 Answers1

0

You need a method to return those items...

see this: https://play.golang.org/p/rnH0riWKqRY


package main

import "fmt"

type Tmp interface {
    MyTmp() string
    Items() []int
}

type MyStructA struct {
    ArrayOfItems []int
}

func (a MyStructA) MyTmp() string {
    return "Hello World"
}

func (a MyStructA) Items() []int {
    return a.ArrayOfItems
}

type MyStructB struct {
    ArrayOfItems []int
}

func (a MyStructB) MyTmp() string {
    return "Hello World B"
}

func (a MyStructB) Items() []int {
    return a.ArrayOfItems
}

func iterate(tmp Tmp) {
    for _, val := range tmp.Items() {
        fmt.Println(val)
    }
}

func main() {
    a := MyStructA{[]int{1, 2, 3}}
    b := MyStructA{[]int{-1, -2, -3}}
    iterate(a)
    iterate(b)

}


Lucas Katayama
  • 4,445
  • 27
  • 34