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) }
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]
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!