英文:
Golang (beginner): Avoiding duplicate functions to deal with strings or ints
问题
我今天开始学习Go语言,所以这可能是一个愚蠢的问题。我习惯了PHP,其中我不需要声明变量类型。
我正在将一些常用的PHP函数转换为Go函数。我有一个函数,它将数组转换为哈希表,以便以后可以快速查找(比通过迭代数组查找值是否存在要快得多,而是将值作为键)。
在我看来,我需要创建两个单独的函数,一个用于字符串,一个用于整数(uint
,因为我不需要有符号整数)。为了方便维护,我希望有一个函数可以接受string
或uint
,并返回相同的类型,即它可以处理并返回我最初传递给函数的类型。
目前我有这样的代码:
// Array2Map_string 将字符串数组转换为哈希表: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 将整数数组转换为哈希表:int=>false
func Array2Map_int(a []uint) map[uint]bool {
mc := make(map[uint]bool)
for _,tok := range a {
mc[tok]=false
}
return mc
}
我想要的是一个单一的函数,如果我将一个字符串数组传递给该函数,它将创建并返回一个基于字符串的哈希表,如果我将一个整数数组传递给该函数,它将创建并返回一个基于整数的哈希表。例如:
// Array2Map 将数组转换为哈希表,键为whatever类型
func Array2Map(a []whatever) map[whatever]bool {
mc := make(map[whatever]bool)
for _,tok := range a {
mc[tok]=false
}
return mc
}
这种做法可行吗?
英文:
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?
答案1
得分: 3
泛型在Go语言中尚不存在(尽管有很多关于它的讨论)。目前来说,我认为你当前的方向是你唯一的选择。
英文:
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.
1: http://www.reddit.com/r/golang/comments/1x7txi/why_generics/ "discussion"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论