Home  >  Article  >  Backend Development  >  Go language map using custom types as keys

Go language map using custom types as keys

WBOY
WBOYOriginal
2024-03-24 17:12:04774browse

Go language map using custom types as keys

Title: Go language map example using custom type as key

In Go language, you can use custom type as key of map, which provides us A more flexible data storage method. By defining custom types, more complex key-value relationships can be implemented to meet specific needs. In this article, we will introduce how to use custom types as map keys in Go language and provide specific code examples.

First, we need to define a custom type as the key of the map. Here we take a structure type as an example:

package main

import "fmt"

type Coordinate struct {
    X int
    Y int
}

func main() {
    // 创建一个以Coordinate为键,字符串为值的map
    coordinateMap := make(map[Coordinate]string)

    // 初始化Coordinate作为键的值
    coord1 := Coordinate{X: 1, Y: 2}
    coord2 := Coordinate{X: 3, Y: 4}

    // 将键值对添加到map中
    coordinateMap[coord1] = "A"
    coordinateMap[coord2] = "B"

    // 获取特定键对应的值
    fmt.Println("coord1对应的值为:", coordinateMap[coord1])
    fmt.Println("coord2对应的值为:", coordinateMap[coord2])

    // 循环遍历map
    for key, value := range coordinateMap {
        fmt.Printf("坐标(%d,%d)对应的值为:%s
", key.X, key.Y, value)
    }
}

In the above code, we define a structure type Coordinate, containing two integer fields X and Y. Then create a mapcoordinateMap with Coordinate as the key and string as the value, and add two sets of key-value pairs to it. Finally, for range loops through the map and outputs the value corresponding to each key value.

Using custom types as map keys allows us to process complex data structures more conveniently and improves the readability and ease of use of the code. Through the above examples, we can see how to use custom types as map keys in the Go language. I hope it will be helpful to you.

The above is the detailed content of Go language map using custom types as keys. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn