In Go, you can create a map with a default value for missing keys by using a custom map type that implements the Getter
method of the map[string]interface{}
interface.
Here's an example code that demonstrates how to create a map with a default value for missing keys:
package main
import "fmt"
type DefaultMap map[string]interface{} // Define a custom map type
func (dm DefaultMap) Get(key string) interface{} {
if value, ok := dm[key]; ok {
return value
}
return "default" // Set the default value for missing keys
}
func main() {
m := DefaultMap{"one": 1, "two": 2, "three": 3}
fmt.Println(m.Get("one")) // Output: 1
fmt.Println(m.Get("four")) // Output: default
fmt.Println(m.Get("five")) // Output: default
fmt.Println(m.Get("six")) // Output: default
}
In the above code, we define a DefaultMap
type that wraps a map[string]interface{}
. This custom type has a Get
method that checks if the requested key exists in the map. If it does, it returns the corresponding value; otherwise, it returns the default value ("default" in this case).
By using this DefaultMap
type, you can create maps with default values for missing keys.