Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang map with multiple keys per value

Tags:

dictionary

go

Consider the following XML data structure:

<MediaItems>
    <item url="media/somefolder/pic1.jpg" id="1">
        <groups>
            <group>1</group>
            <group>2</group>
        </groups>
    </item>
    <item url="media/somefolder/pic2.jpg" id="2">
        <groups>
            <group>3</group>
            <group>7</group>
        </groups>
    </item>
</MediaItems>

Since my XML data structure/file can potentially scale to 10000 or perhaps 100000+ media item elements, I need to be able to access the individual items, in the parsed Go map (or what structure to use here?), like we do with map[key]type - but I need to be able to use either the url or the id as a key, and I can't figure out how to create a map with 2 keys pointing to the same value.

From the parsed XML data structure above, I need to parse it in Go and store it in a type like:

map[string, string]MediaItem

Where the keys should be url and id, so I'd be able to get the item with id 1 doing myMap["1"] or myMap["media/somefolder/pic1.jpg"]. Both should return the corresponding MediaItem.)

I can't wrap my head around how to implement this, or maybe there a better way to achieve the same?

like image 985
Dac0d3r Avatar asked Dec 28 '25 16:12

Dac0d3r


1 Answers

Better solution would be to use struct with two field as a key:

type key struct {
    url string
    id  int
}

m := make(map[key]MediaItem)
m[key{url: "http://...", id: 2}] = MediaItem{}
like image 122
abonec Avatar answered Dec 30 '25 11:12

abonec