Newbie in golang.
func OutputMe(mainContent []any, dimX, dimY byte, strategy string) (message string, e error)
try to pass []int{1,2,35}
and always get an error
cannot use []int{…} (value of type []int) as []any value
what am i doing wrong?
Newbie in golang.
func OutputMe(mainContent []any, dimX, dimY byte, strategy string) (message string, e error)
try to pass []int{1,2,35}
and always get an error
cannot use []int{…} (value of type []int) as []any value
what am i doing wrong?
Oi! Can you please format this code? Put the shared code inside an code snippet block, you can just select the code and use the </> button
package main
func main() {
// ...code code
}
Please share more about the code, It’s kinda hard to understand what you are trying to do
was thinking that is possible to implement some method with []any
and then provide []integer{1,2,3,4,-6}
like an argument
Go has strong static typing model and type []any
implies you to use exactly this type, not another. What you are trying to do is generic programming, e.g.,
func fn[T []E, E any](sl T) {
// Your code goes here...
}
But in this case you need to guarantee, that the code in your function will be able to handle any
, since it’s every possible type. Imho, if you are not using generics, it is better to define exact type of the argument.
I think change ny to just only any, so
func OutputMe(mainContent any, dimX, dimY byte, strategy string) (message string, e error)
Then if you are working with []int
inside the function, you will need to do type assertion.
Obviously you don’t understand the data structure, []int
is an array of integers, let’s say it’s in a 64-bit system, then each element occupies 64 bits, []any
, where any is the pointer, and the pointer occupies 64 bits. Although it seems, both occupy 64 bits, []string
and []any
, can you guarantee that string takes 64 bits? So []any
is not the same as any slice. You should iterate over []int
and stuff it into []any
.
go doesnt support implicit type conversions between slices. theres no way to cast []any
between other data structures in go.
also, the data structure of []any
is an empty interface that stores pointers to values of different types, while []int
stores values directly.
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.