create a map with a value of type int in go

In Go, maps are a built-in data structure used to associate a key with a value. Here's an example of how to create a map with a value of type int:

main.go
// declare a variable to hold our map
var myMap map[string]int

// create the map using the make function
myMap = make(map[string]int)

// add values to the map
myMap["apple"] = 2
myMap["banana"] = 4

// access the values in the map
fmt.Println("Number of apples:", myMap["apple"]) // prints "Number of apples: 2"
fmt.Println("Number of oranges:", myMap["orange"]) // prints "Number of oranges: 0"
398 chars
14 lines

In the code snippet above, we first declare a variable myMap of type map[string]int, which means it maps strings to integers.

We then initialize the map using the built-in make function in Go. The make function takes two arguments: the type of the map (in this case, map[string]int) and an optional initial capacity (which we've omitted in this example).

We then add key-value pairs to the map using the square bracket notation: mapName[key] = value

Finally, we can access values in the map using the same square bracket notation, like this: mapName[key]. Note that if the key doesn't exist in the map, Go will return the zero value for that particular map value type.

related categories

gistlibby LogSnag