Can Slices Be Used as Map Keys in Go?

DDD
Release: 2024-11-12 04:22:01
Original
480 people have browsed it

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

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

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.

The above is the detailed content of Can Slices Be Used as Map Keys in Go?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template