ashok poudel
ashok poudel

Reputation: 723

Dynamic array struct as parameter

How can I pass a dynamic array struct as parameter in golang

For e.g

type Dog {
  Name string 
}

type Cat {
  Name uint
}

I want a function which takes array of either cat or dog as an argument and loop through the array in the function . Below is function of what I wanna achive

func (array of either cats or dogs ){

    for _ , item := range (array of either cats or dogs) {

   }  
 }

Upvotes: 1

Views: 774

Answers (2)

Tomasz Giba
Tomasz Giba

Reputation: 541

interface{} is one way to go, as mentioned in Answers.

I find the other interfaces also useful:


import (
    "fmt"
)

type Pet interface{}

type Dog struct {
    Pet
    Name string
}

type Cat struct {
    Pet
    Name uint
}

func listPets(pets []Pet) {
    for _, pet := range pets {
        fmt.Println(pet)
    }
}

func main() {
    pets := []Pet{Dog{Name: "Rex"}, Dog{Name: "Boss"}, Cat{Name: 394}}
    listPets(pets)
}

https://play.golang.org/p/uSiYmcrSuqJ

Upvotes: 1

Omkar Rokade
Omkar Rokade

Reputation: 120

I am assuming you mean

type Dog struct{
  Name string 
}

type Cat struct{
  Name uint
}

Your function should accept interface{} as an argument, so you are free to send either Dog or Cat or whatever you want as an argument. But after accepting the data you need to apply Type assertion inside the function to extract the specific data type in order to loop over it as you can't loop over the interface.

x := args.(type) // x will contain the name of the data type store inside the interface{}

Or you could use

x := i.(Dog) //if you're absolutely sure that the data type is Dog

x, ok := i.(Cat) //If you're not sure and want to avoid runtime panic

Please read the Go Tour examples to learn more about type assertions.

Edit: In the comments @mkopriva suggested func F(slice ...interface{}), so you need to convert the slice of Dog or Cat to slice of interface{} for that function signature to work. You will have manually to add/append each element in the Cat or Dog slice to an interface{} slice to convert from slice of Cat or Dog to slice of interface{} slice.

Upvotes: 1

Related Questions