Home > Mobile >  How can I pass a slice of any object as a slice of interface{} to a function?
How can I pass a slice of any object as a slice of interface{} to a function?

Time:03-25

I have this piece of code:

package main

import "fmt"

type Any interface{}

func foo(anys []Any) {
    for _, any := range anys {
        // do something
        fmt.Println(any)
    }
}

func main() {
    foo([]int{1, 2, 3})
}

I expected it would work since Any is the same as interface{}. But, I am getting the following error:

cannot use []int{…} (value of type []int) as type []Any in argument to foo

What concept of interface{} did I get wrong? Is there any way to make it work safely?

CodePudding user response:

Use slice of any

package main

import "fmt"

func foo(anys []any) {
    for _, val := range anys {
        fmt.Println(val)
    }
}

func main() {
    foo([]any{1, 2, 3})
}

Or use generics:

package main

import "fmt"

func foo[T any](anys []T) {
    for _, val := range anys {
        fmt.Println(val)
    }
}

func main() {
    foo([]int{1, 2, 3})
}

CodePudding user response:

This will work. You can run the code here: https://play.golang.com/p/OjWDK9GJL1f

func main() {
    foo([]Any{1,2,3})
}

Not sure if that's the best thing for your problem.

  •  Tags:  
  • go
  • Related