create a map with a value of type string in go

To create a map with a value of type string in Go, declare the map using the map keyword and specify the data types for both the key and the value. For example, to create a map with string keys and string values, use:

main.go
myMap := make(map[string]string)
33 chars
2 lines

This creates an empty map with string keys and string values. You can add key-value pairs to the map using the [] operator. For example:

main.go
myMap["foo"] = "bar"
21 chars
2 lines

This adds a key-value pair to the map where the key is "foo" and the value is "bar". You can retrieve the value of a key from the map using the [] operator as well:

main.go
val := myMap["foo"]
20 chars
2 lines

This retrieves the value of the "foo" key from the map and assigns it to the val variable.

You can also use the map literal syntax to initialize a map with some key-value pairs:

main.go
myMap := map[string]string{
    "foo": "bar",
    "baz": "qux",
}
66 chars
5 lines

This creates a map with two key-value pairs: "foo" => "bar" and "baz" => "qux".

related categories

gistlibby LogSnag