How to write func for a generic parameter in golang

I am trying to write a Map function so that it can handle all types of arrays.

 // Interface to specify generic type of array. type Iterable interface { } func main() { list_1 := []int{1, 2, 3, 4} list_2 := []uint8{'a', 'b', 'c', 'd'} Map(list_1) Map(list_2) } // This function prints the every element for // all []types of array. func Map(list Iterable) { for _, value := range list { fmt.Print(value) } } 

But it throws a compile-time error.

 19: cannot range over list (type Iterable) 

The error is correct, because range requires an array, a pointer to an array, slice, line, map or channel that allows receiving operations, and here it is Iterable . I think the problem I am facing is converting the type of the Iterable argument to an array type. Please suggest how I could use my function to process a shared array.

+7
function arrays go
source share
2 answers

As Rob Pike says in this thread

Is it possible to express “any map”, “any array” or “any slice” in a Go type switch?

Not. Static types must be exact .
An empty interface is really a type, not a wildcard.

You can only iterate over a list of a certain type, for example, an interface with known functions.
You can see an example with. Can we write a general array / fragment deduplication in go? "

Even using reflection, passing the slice as interface{} will, as this thread shows , is error prone (see this example ).

+5
source share

Your map definition is incorrect. The usual way to declare it will be with the mapper method. Your example can be implemented in at least this way.

 package main import "fmt" // Interface to specify something thet can be mapped. type Mapable interface { } func main() { list_1 := []int{1, 2, 3, 4} list_2 := []string{"a", "b", "c", "d"} Map(print, list_1) Map(print, list_2) } func print(value Mapable){ fmt.Print(value) } // This function maps the every element for // all []types of array. func Map(mapper func(Mapable), list ... Mapable) { for _, value := range list { mapper(value) } } 

It works . It must be said that this is a little untyped. Because no, Go has no “generics” in the sense of Hindley-Milner

0
source share

All Articles