# Maps

Maps are a built-in associative data-structure in golang that allows us to store data in key-value pairs. Maps are synonymous to hashes or dicts in other languages. Below, we will go over some of the basics of maps in golang

#### Creating a new map

To create a new map, we use the `make` keyword

{% code lineNumbers="true" %}

```go
package main
import "fmt"

func main() {
  vending_machine := make(map[string]int)
  vending_machine["coke"] = 9
  vending_machine["beer"] = 3
  vending_machine["water"] = 24
  fmt.Println("number of items: ", len(vending_machine")
  fmt.Println("vending machine items", vending_machine)
  
  // we can also declare and init a map as follows
  inventory := map[string]int{"pepsi": 10, "sprite": 4, "rootbeer": 1}
  fmt.Println("inventory: ", inventory)
}
```

{% endcode %}

#### Get, update, delete, items in maps

We can add, delete, and change values of items in a map

{% code lineNumbers="true" %}

```go
package main
import "fmt"

func main() {
  vending_machine := make(map[string]int)
  vending_machine["coke"] = 9
  vending_machine["beer"] = 3
  vending_machine["water"] = 24
  fmt.Println("number of items: ", len(vending_machine")
  fmt.Println("vending machine items", vending_machine)
  
  coke_price := m["coke"]
  fmt.Println("number of coke bottles: ", coke_price)
  
  // the built-in method, delete removes the item from the map
  delete(vending_machine, "water")
  fmt.Println("vending machine ran out of water:", vending_machine)
  fmt.Println(len(vending_machine))
}
```

{% endcode %}

{% hint style="info" %}
We can get the value of a map item using it's key. However, we may be interested in knowing if the key existed or not when getting the value. We do so by using the syntax

```go
value, key_present = vending_machine["tea"]
// value: nil
// key_present: false
```

This method can be used to disambiguate between missing keys and keys with zero values like `0` or `""`.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://golang.collingrimm.com/data-structures/maps.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
