Home > Backend Development > Golang > How can I use slices as keys in a Go map?

How can I use slices as keys in a Go map?

Patricia Arquette
Release: 2024-11-13 07:12:02
Original
492 people have browsed it

How can I use slices as keys in a Go map?

Using Slices as Map Keys

While the compiler prohibits the usage of slices as direct map keys due to their mutable nature, an alternative approach can be employed: converting slices to arrays before using them as keys.

Example:

package main

import "fmt"

func main() {
    h := make(map[[2]string]string)
    h[[2]string{"a", "b"}] = "ab"

    fmt.Printf("%v", h)
}
Copy after login

In this example, a map where the keys are arrays of strings is created. The type of the map key is explicitly defined as [2]string, which is an array of strings with a fixed size of 2.

Explanation:

Since arrays are immutable in Go, they adhere to the requirements of being a valid map key. This allows you to effectively use slices as keys by converting them to fixed-size arrays. Arrays offer the necessary immutability and uniqueness, ensuring reliable and consistent map operations.

The above is the detailed content of How can I use slices as keys in a Go 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