简体   繁体   English

包含切片的结构集

[英]Set of structs containing a slice

I'm trying to implement a toy search algorithm and need to maintain a set of explored states. 我正在尝试实现玩具搜索算法,并且需要维护一组探索状态。 A state is a struct: 状态是一个结构:

type VWState struct {
    botLocation   VWCoords
    dirtLocations []VWCoords
}

My first thought was that a simple Set could be implemented using a map[VWState]bool , but I can't seem to figure out a way to make it work. 我的第一个想法是可以使用map[VWState]bool实现一个简单的Set,但是我似乎还没有找到使它起作用的方法。 If I try to use a VWState as a key to a map, I get the following panic: 如果尝试使用VWState作为地图的键, VWState出现以下恐慌:

Panic: runtime error: hash of unhashable type vw.VWState (PC=0x40EB0D)

Is there a way to make this work? 有没有办法使这项工作? Can I implement a custom hashing function for the struct, or should I be looking at some other ways to implement this? 我可以为该结构实现自定义哈希函数,还是应该寻找其他实现此结构的方法?

Any help would be greatly appreciated. 任何帮助将不胜感激。

You can use a pointer to your struct as a map key: 您可以将指向结构的指针用作映射键:

map[*VWState]bool

If you want to be able to compare equivalent structs, you can create a method to output a key for the map. 如果您希望能够比较等效的结构,则可以创建一种方法来输出地图的键。 String() would be convenient, since you could also use it to print your struct, or tie in a hash function and output something shorter, even an int . String()会很方便,因为您还可以使用它来打印您的结构,或者绑定一个哈希函数并输出更短的内容,甚至是一个int

Something as simple as this may suffice, though you could make the output shorter if you like (being careful not to recursively call String() in your format line): 尽管您可以根据需要将输出缩短(请注意不要在格式行中递归调用String() ,但这样的简单操作就足够了:

func (s VWState) String() string {
    return fmt.Sprintf("%#v", s)
}

func main() {
    m := make(map[string]bool)
    s := VWState{}
    m[s.String()] = true
}

If there is a sensible maximum length for dirtLocations then you could use an array instead of a slice. 如果dirtLocations有合理的最大长度,则可以使用数组而不是切片。 Arrays are hashable (provided the element is hashable). 数组是可哈希的(假设元素是可哈希的)。

type VWState struct {
    botLocation   VWCoords
    dirtLocations [4]VWCoords
}

You'll then need to either add a count of the number of valid dirtLocations or detect the zero value of VWCoords to work out how many slots in dirtLocations are valid. 然后,您需要添加有效dirtLocations数量的dirtLocations或检测dirtLocations的零值来VWCoords dirtLocations有多少个插槽有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM