Beginner in golang.func OutputMe(mainContent []any, dimX, dimY byte, technique string) (message string, e error)
attempt to cross []int{1,2,35}
and all the time get an error
can't use []int{…} (worth of kind []int) as []any worth
what am i doing unsuitable?
Oi! Are you able to please format this code? Put the shared code inside an code snippet block, you possibly can simply choose the code and use the </> button
package deal predominant
func predominant() {
// ...code code
}
Please share extra in regards to the code, It’s kinda arduous to grasp what you are attempting to do
was pondering that’s attainable to implement some methodology with []any
after which present []integer{1,2,3,4,-6}
like an argument
Go has sturdy static typing mannequin and sort []any
implies you to make use of precisely this kind, not one other. What you are attempting to do is generic programming, e.g.,
func fn[T []E, E any](sl T) {
// Your code goes right here...
}
However on this case you should assure, that the code in your operate will be capable of deal with any
, because it’s each attainable kind. Imho, if you’re not utilizing generics, it’s higher to outline actual kind of the argument.
1 Like
I feel change ny to simply solely any, so
func OutputMe(mainContent any, dimX, dimY byte, technique string) (message string, e error)
Then if you’re working with []int
contained in the operate, you will want to do kind assertion.
Clearly you don’t perceive the information construction, []int
is an array of integers, let’s say it’s in a 64-bit system, then every aspect occupies 64 bits, []any
, the place any is the pointer, and the pointer occupies 64 bits. Though it appears, each occupy 64 bits, []string
and []any
, are you able to assure that string takes 64 bits? So []any
is just not the identical as any slice. It is best to iterate over []int
and stuff it into []any
.
go doesnt assist implicit kind conversions between slices. theres no solution to forged []any
between different knowledge constructions in go.
additionally, the information construction of []any
is an empty interface that shops tips to values of various sorts, whereas []int
shops values immediately.