×

Go Tutorial

Go Basics

Go Variables

Go Literals

Go Type Handling

Go Operators

Go Decision Making

Go Loops

Go Functions

Go String

Go Arrays

Go Slices

Go Maps

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Access Map Elements in Go

Last Updated : May 27, 2025

In Go, you can access elements in a map using the key inside square brackets. If the key exists, the corresponding value is returned. If the key is not present, a zero value for the value type is returned.

Accessing Map Elements by Key

Use the key inside square brackets to retrieve a value from a map.

Example

This example shows how to access values using keys in a map:

package main
import "fmt"

func main() {
    countries := map[string]string{
        "IN": "India",
        "US": "United States",
        "FR": "France",
    }

    fmt.Println("IN:", countries["IN"])
    fmt.Println("US:", countries["US"])
    fmt.Println("FR:", countries["FR"])
}

When executed, this program outputs:

IN: India
US: United States
FR: France

Accessing a Non-Existing Key

If you try to access a key that doesn't exist, Go returns the zero value for the map's value type.

Example

This example attempts to access a non-existing key:

package main
import "fmt"

func main() {
    marks := map[string]int{
        "Rahul": 85,
        "Sneha": 92,
    }

    fmt.Println("Marks of Rahul:", marks["Rahul"])
    fmt.Println("Marks of Amit:", marks["Amit"]) // Key not present
}

When executed, this program outputs:

Marks of Rahul: 85
Marks of Amit: 0

Using Value with Existence Check

You can use the second return value to check if a key exists in the map.

Example

This example shows how to check if a key exists using the comma-ok idiom:

package main
import "fmt"

func main() {
    fruits := map[string]int{
        "Apple":  10,
        "Banana": 20,
    }

    qty, exists := fruits["Apple"]
    if exists {
        fmt.Println("Apple is available with quantity:", qty)
    }

    qty, exists = fruits["Mango"]
    if !exists {
        fmt.Println("Mango is not available")
    }
}

When executed, this program outputs:

Apple is available with quantity: 10
Mango is not available

Exercise

Select the correct answer for each question about accessing map elements in Go.

  1. What is returned when you access a non-existent key in a map of type map[string]int?
  2. How can you check if a key exists in a Go map?
  3. What happens if you try to access a key in a nil map?

Advertisement
Advertisement

Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

Copyright © 2025 www.includehelp.com. All rights reserved.