Home  >  Article  >  Backend Development  >  Can Slices Be Used as Keys in a Map?

Can Slices Be Used as Keys in a Map?

Linda Hamilton
Linda HamiltonOriginal
2024-11-18 03:27:02831browse

Can Slices Be Used as Keys in a Map?

Can Slices Be Utilized as Map Keys?

The question arises whether slices can function effectively as keys within a map data structure. An attempt to implement such a scenario is illustrated below:

h := map[[]string]string{
  []string{"a", "b"} : "ab",
}

However, this code encounters an error stating that the map key type, "[]string," is invalid. This suggests that slices cannot be directly used as map keys.

Utilize an Array as a Map Key

Alternatively, arrays can be successfully employed as map keys. This is demonstrated by the following code:

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, an array of length two is utilized as the map key. This code executes successfully, demonstrating that arrays can serve as valid map keys.

The above is the detailed content of Can Slices Be Used as Keys in a Map?. 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