如何在Go中使用任意长度的值序列作为映射键?

huangapple go评论80阅读模式
英文:

How to use arbitrary length sequences of values as map keys in Go?

问题

编辑:Jeremy Wall帮助我意识到我提出了一个比我打算的更具体的问题;这是一个更好的版本。

假设我想要表示一个表,将某种类型B的值与某种类型A的值序列关联起来,其中定义了相等性。在Go中,最好的方法是什么?

显然,对于表,我想要使用Go的映射,但是对于类型A的值序列,我可以使用什么?在Go中,切片不能用作映射的键;数组可以,但是数组的长度是其类型的一部分,而我希望能够使用在运行时确定的长度的序列。我可以(1)使用声明了最大长度的A数组,或者(2)使用A切片,将它们序列化为字符串以用作键(这种技术对Awk和Lua程序员来说很熟悉...)。除了我描述的这些方法之外,是否有更好的解决办法来解决Go的这个“特性”?

正如Jeremy Wall在回答我原始版本的问题时指出的那样,当A = int时,选项(2)对于整数来说非常好,因为您可以使用符文切片,将其转换为字符串只是一个强制转换。

英文:

Edit: Jeremy Wall helped me realize I had asked a question more specific than I intended; here's a better version.

Say I want to represent a table associating of values of some type B to sequences of values of some type A for which equality is defined. What is the best way to do that in Go?

Obviously for the table I'd want to use a Go map, but what can I use for the sequences of values of type A? Slices cannot be used as keys for maps in Go; arrays can, but the length of an array is a part of it's type and I'm interested in being able to use sequences of length determined at runtime. I could (1) use arrays of A declaring a maximum length for them or (2) use slices of A, serialize them to strings for use as keys (this technique is familiar to Awk and Lua programmers...). Is there a better work around for this "feature" of Go than the ones I've described?

As pointed out by Jeremy Wall in answer to my original version of the question, where I had A = int, option (2) is pretty good for integers, since you can use slices of runes for which conversion to string is just a cast.

答案1

得分: 1

你是否希望使用rune序列而不是整数?runes是uint32类型,将其转换为字符串只需进行强制类型转换:

package main

import "fmt"

type myKey struct {
  seq []int
}

func main() {
    m := make(map[string]string)
    key := []rune{1, 2}
    m[string(key)] = "foo"
    fmt.Print("lookup: ", m[string(key)])
}

你可以在这里尝试运行这段代码:http://play.golang.org/p/Kct1dum8A0

英文:

Will a sequence of rune instead of integers work for you? runes are uint32 and the conversion to a string is just a cast:

package main

import "fmt"

type myKey struct {
  seq []int
}

func main() {
	m := make(map[string]string)
	key := []rune{1, 2}
	m[string(key)] = "foo"
	fmt.Print("lookup: ", m[string(key)])
}

You can play with this code here: http://play.golang.org/p/Kct1dum8A0

huangapple
  • 本文由 发表于 2012年4月12日 10:06:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/10116476.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定