简体   繁体   中英

Dynamic array struct as parameter

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

For eg

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) {

   }  
 }

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM