天涯尽头无女友
例如,package mainimport "fmt"type Tag struct { Key string Value string}type Tags []Tagtype TagsValue struct { // some type used as Tags value}type TagsMapValue struct { Tags TagsValue}type TagsMapKey stringtype TagsMap map[TagsMapKey]TagsMapValuefunc NewTagsMapKey(tags Tags) TagsMapKey { b := []byte{} for _, tag := range tags { b = append(b, tag.Key...) b = append(b, tag.Value...) } return TagsMapKey(b[:len(b)])}func (m *TagsMap) AddElement(tags Tags, tagsValue TagsValue) { mapKey := NewTagsMapKey(tags) mapValue := TagsMapValue{Tags: make(Tags, 0, len(tags)), TagsValue: tagsValue} i := 0 for _, tag := range tags { key := string(mapKey[i : i+len(tag.Key)]) i += len(tag.Key) value := string(mapKey[i : i+len(tag.Value)]) i += len(tag.Value) mapValue.Tags = append(mapValue.Tags, Tag{Key: key, Value: value}) } (*m)[mapKey] = mapValue return}func main() { m := make(TagsMap) sortedTags := Tags{ {Key: "key1", Value: "value1"}, {Key: "key7", Value: "value7"}, {Key: "key7", Value: "value49"}, {Key: "key42", Value: "value42"}, } m.AddElement(sortedTags, TagsValue{}) for k, v := range m { fmt.Println("Tags Key:", k) fmt.Println(" Tags: ", v.Tags) fmt.Println(" Tags Value:", v.TagsValue) }}输出:Tags Key: key1value1key7value7key7value49key42value42 Tags: [{key1 value1} {key7 value7} {key7 value49} {key42 value42}] Tags Value: {}如果您只是想测试标签集成员资格,package mainimport "fmt"type Tag struct { Key string Value string}type Tags []Tagtype TagsSetKey stringtype TagsSet map[TagsSetKey]Tagsfunc NewTagsSetKey(tags Tags) TagsSetKey { b := []byte{} for _, tag := range tags { b = append(b, tag.Key...) b = append(b, tag.Value...) } return TagsSetKey(b[:len(b)])}func (m *TagsSet) AddElement(tags Tags) { setKey := NewTagsSetKey(tags) setValue := make(Tags, 0, len(tags)) i := 0 for _, tag := range tags { key := string(setKey[i : i+len(tag.Key)]) i += len(tag.Key) value := string(setKey[i : i+len(tag.Value)]) i += len(tag.Value) setValue = append(setValue, Tag{Key: key, Value: value}) } (*m)[setKey] = setValue return}func (m *TagsSet) IsMember(tags Tags) bool { return (*m)[NewTagsSetKey(tags)] != nil}func main() { m := make(TagsSet) sortedTags := Tags{ {Key: "key1", Value: "value1"}, {Key: "key7", Value: "value7"}, {Key: "key7", Value: "value49"}, {Key: "key42", Value: "value42"}, } m.AddElement(sortedTags) for k, v := range m { fmt.Println("Tags Key:", k) fmt.Println(" Tags: ", v) } // In set fmt.Println(m.IsMember(sortedTags)) // Not in set sortedTags[0].Key = "key0" fmt.Println(m.IsMember(sortedTags))}输出:Tags Key: key1value1key7value7key7value49key42value42 Tags: [{key1 value1} {key7 value7} {key7 value49} {key42 value42}]truefalse