Maps in Go

Maps in Go are unordered collections of key-value pairs. The keys must be unique and of a comparable type, while the values can be of any type. Maps are a useful data structure for storing and retrieving data based on keys.

Creating Maps

To create a map, you use the make function and specify the key and value types:

Go

fruits := make(map[string]int)

This creates a map where the keys are strings and the values are integers.

Adding and Retrieving Elements

You can add or retrieve elements from a map using the key:

Go

fruits["apple"] = 5
count := fruits["banana"]

Checking for Keys

To check if a key exists in a map, you can use the comma ok idiom:

Go

if value, ok := fruits["orange"]; ok {
    fmt.Println("Orange count:", value)
} else {
    fmt.Println("Orange not found")
}

Deleting Elements

To delete an element from a map, use the delete function:

Go

delete(fruits, "apple")

Iterating over Maps

You can iterate over the key-value pairs in a map using a for range loop:

Go

for key, value := range fruits {
    fmt.Println(key, value)
}

Maps and gRPC

Maps can be used in gRPC services to represent structured data. For example, you might use a map to store metadata about a resource.

Example:

Protocol Buffers

message User {
  string id = 1;
  string name = 2;
  map<string, string> metadata = 3;
}

Go

type userService struct{}

func (s *userService) GetUser(ctx context.Context, in *pb.GetUserRequest) (*pb.User, error) {
  user := &pb.User{
    Id: "user1",
    Name: "Alice",
    Metadata: map[string]string{
      "email": "[email protected]",
      "role":  "admin",
    },
  }
  return user, nil
}
Understand Slices in Go
Working with Structs

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?