"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can Slices Be Used as Map Keys in Go?

Can Slices Be Used as Map Keys in Go?

Published on 2024-11-11
Browse:273

Can Slices Be Used as Map Keys in Go?

Using Slices and Arrays as Map Keys

In Go, map keys must implement the == and != operators to compare their equality. Slices do not implement these operators, so slices cannot be used directly as map keys. However, arrays can be used as map keys because they implement the necessary operators.

Using Arrays as Map Keys

To use an array as a map key, you can declare the map using the array type as the key type. For example:

package main

import "fmt"

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

This map has a key type of [2]int, which is an array of two integers. The value type of the map is bool.

Using Slices by Converting to Strings

If you need to use a slice as a map key, you can convert the slice to a string and use the string as the key. For example:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    m := make(map[string]bool)
    m[strconv.Itoa([]string{"a", "b"})] = false
    fmt.Printf("%v", m)
}

This map has a key type of string, which is a string representation of the slice of strings. The value type of the map is bool.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3