How to create a map with case-insensitive string keys in Go?

In Go, the built-in map data structure does not directly support case-insensitive string keys. However, you can create a custom map implementation that wraps the map[string]value and handles case-insensitive string keys. Here is an example of how you can achieve this:

package main import ( "fmt" "strings" ) type CaseInsensitiveMap struct { m map[string]interface{} } func NewCaseInsensitiveMap() *CaseInsensitiveMap { return &CaseInsensitiveMap{ m: make(map[string]interface{}), } } func (cim *CaseInsensitiveMap) Set(key string, value interface{}) { cim.m[strings.ToLower(key)] = value } func (cim *CaseInsensitiveMap) Get(key string) (interface{}, bool) { val, ok := cim.m[strings.ToLower(key)] return val, ok } func main() { cim := NewCaseInsensitiveMap() cim.Set("Key", "Value") val, ok := cim.Get("key") if ok { fmt.Println(val) // Output: Value } }

In this example, the CaseInsensitiveMap wraps a map[string]interface{}. The Set() method converts the key to lowercase using the strings.ToLower() function before storing the value in the internal map. The Get() method also converts the key to lowercase while retrieving the value. This way, any string keys provided to Set() or Get() will be treated as case-insensitive.

You can add additional methods to the CaseInsensitiveMap type as per your requirement, such as a Delete() method to remove a key-value pair, or a Keys() method to retrieve all the keys.