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

Can Slices Be Used as Keys in a Map?

Linda Hamilton
Release: 2024-11-18 03:27:02
Original
885 people have browsed it

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",
}
Copy after login

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)
}
Copy after login

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!

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