0
0
Goprogramming~5 mins

Accessing map values in Go

Choose your learning style9 modes available
Introduction

Maps store pairs of keys and values. Accessing map values lets you find information quickly using a key.

You want to find a phone number by a person's name.
You need to get a product price using its ID.
You want to check if a username exists in a list.
You want to count how many times a word appears in a text.
Syntax
Go
value, ok := mapName[key]

value gets the data stored for key.

ok is a boolean that is true if the key exists, false if not.

Examples
Get the value for key "Alice" without checking if it exists.
Go
age := ages["Alice"]
Get value and check if "Bob" exists before using it.
Go
age, ok := ages["Bob"]
if ok {
    fmt.Println("Bob's age is", age)
} else {
    fmt.Println("Bob not found")
}
Sample Program

This program shows how to get values from a map. It prints Alice's age and checks if Charlie is in the map before printing.

Go
package main

import "fmt"

func main() {
    ages := map[string]int{"Alice": 30, "Bob": 25}

    // Access value directly
    aliceAge := ages["Alice"]
    fmt.Println("Alice's age:", aliceAge)

    // Access with check
    charlieAge, ok := ages["Charlie"]
    if ok {
        fmt.Println("Charlie's age:", charlieAge)
    } else {
        fmt.Println("Charlie not found in map")
    }
}
OutputSuccess
Important Notes

If you access a key that does not exist without checking, Go returns the zero value for the value type (like 0 for int).

Always check the boolean ok if you need to know whether the key was present.

Summary

Maps store key-value pairs for quick lookup.

Use value, ok := map[key] to get a value and check if the key exists.

Without checking, missing keys return zero values.