Can Arrays Be Used as Map Keys in Go?

Susan Sarandon
Release: 2024-11-17 07:16:03
Original
354 people have browsed it

Can Arrays Be Used as Map Keys in Go?

Using Arrays Instead of Slices in Map Keys

While using slices as map keys directly may not be possible, it is feasible to employ arrays as keys instead. Here's how:

For instance, the following Go code successfully uses an array as a map key:

package main

import "fmt"

func main() {
    m := make(map[[2]int]bool)
    m[[2]int{1, 2}] = false
    fmt.Printf("%v", m)
}
Copy after login

In this example, we create a map with a key type of array. The array key is defined as [2]int, which specifies an array of length 2 containing integers. We then assign a boolean value to the map using an array as the key.

When we run the code, the output is:

map[[2]int:1 2:false]
Copy after login

This demonstrates that it is possible to use arrays as map keys in Go. Note that the array key type must be a valid type that can be compared for equality, and the array must have a fixed length.

The above is the detailed content of Can Arrays Be Used as Map Keys in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template