Composite keys
You need composite keys when you have multiple values that identify a particular object. For example, say you are dealing with a system where users may have multiple sessions. You can store this information in a map of maps, or you can create a composite key containing the user ID and session ID.
How to do it...
Use a comparable struct or an array as the map key. A comparable struct is, in general, a struct that does not contain the following:
- Slices
- Channels
- Functions
- Maps
- Other non-comparable structs
So, to use composite keys, perform the following steps:
- Define a comparable struct:
type Key struct { UserID string SessionID string } type User struct { Name string ... } var compositeKeyMap = map[Key]User{}
- Use an instance of the map key to access elements:
compositeKeyMap[Key{ UserID: "123", SessionID: "1", ...