I've started learning Go today, so this may be a silly question. I'm used to PHP whereby I don't have to declare variable types.
I'm currently converting some of my commonly used PHP functions into Go functions. I have a function which converts an array into a hashtable for fast lookups later on (much faster than iterating through the array to see if a value exists, instead the values become keys.)
It seems to me that I have to create two separate functions, one for strings and one for integers (uint
as I don't need signed integers). For the sake of maintenance I would prefer to have one function that can accept either string
or uint
and return the same, i.e. it works in and returns whatever I originally pass to the function.
Currently I have this:
// Array2Map_string makes a map out of an array of strings: word=>false
func Array2Map_string(a []string) map[string]bool {
mc := make(map[string]bool)
for _,tok := range a {
mc[tok]=false
}
return mc
}
// Array2Map_int makes a map out of an array of integers: int=>false
func Array2Map_int(a []uint) map[uint]bool {
mc := make(map[uint]bool)
for _,tok := range a {
mc[tok]=false
}
return mc
}
What I would like is to have a single function that will create and return a string based hashtable if I send a string array to the function, or a uint based hashtable if I send a uint array to the function. Example:
// Array2Map makes a map out of an array of strings whereby the key is
func Array2Map(a []whatever) map[whatever]bool {
mc := make(map[whatever]bool)
for _,tok := range a {
mc[tok]=false
}
return mc
}
Is that possible?
Generics don't exist in Go yet (although there is a lot of discussion about it. For now, I think your current direction is your only option.