Golang

关注公众号 jb51net

关闭
首页 > 脚本专栏 > Golang > Golang作为map的key的类型

详解Golang中哪些类型可以作为map的key

作者:路多辛

在 Go 语言中,map 是一种内置的关联数据结构类型,由一组无序的键值对组成,每个键都是唯一的,并与一个对应的值相关联,本文将详细介绍哪些类型的变量可以作为 map 的键,并通过实例进行说明,感兴趣的朋友可以参考下

可以作为 map 键的类型

因为 map 需要能够判断两个键是否相等以确保每个键的唯一性,所以并非所有类型都可以作为 map 的键,可以作为 map 键的数据类型必须满足以下条件:

以下是可以作为 map 键的类型:

package main
 
import "fmt"
 
func main() {
	// 整数作为键
	mapInt := map[int]string{
		1: "one",
		2: "two",
		3: "three",
	}
  
	// 字符串作为键
	mapString := map[string]int{
		"Alice": 25,
		"Bob":   30,
		"Eve":   22,
	}
  
	// 浮点数作为键(不推荐,因为浮点数的比较可能会因精度问题导致不准确)
	mapFloat64 := map[float64]string{
		1.1: "one point one",
		2.2: "two point two",
		3.3: "three point three",
	}
 
	// 布尔值作为键
	mapBool := map[bool]string{
		true:  "true",
		false: "false",
	}
	fmt.Println(mapInt, mapString, mapFloat64, mapBool)
}
package main
 
import "fmt"
 
func main() {
    type Person struct {
       Name string
       Age  int
    }
 
    alice := &Person{"Alice", 25}
    bob := &Person{"Bob", 30}
 
    mapPointer := map[*Person]string{
       alice: "Alice's pointer",
       bob:   "Bob's pointer",
    }
    fmt.Println(mapPointer)
}
package main
 
import "fmt"
 
type Equalizer interface {
    Equal(Equalizer) bool
}
 
type IntEqualizer int
 
func (i IntEqualizer) Equal(e Equalizer) bool {
    other, ok := e.(IntEqualizer)
    return ok && i == other
}
 
func main() {
    mapInterface := map[Equalizer]string{
       IntEqualizer(1): "one",
       IntEqualizer(2): "two",
       IntEqualizer(3): "three",
    }
    fmt.Println(mapInterface)
}
package main
 
import "fmt"
 
func main() {
    type Point struct {
       X, Y int
    }
 
    mapStruct := map[Point]string{
       {1, 2}: "Point at (1,2)",
       {3, 4}: "Point at (3,4)",
    }
    fmt.Println(mapStruct)
}
package main
 
import "fmt"
 
func main() {
    arr1 := [3]int{1, 2, 3}
    arr2 := [3]int{4, 5, 6}
    mapArray := map[[3]int]string{
       arr1: "123",
       arr2: "456",
    }
    fmt.Println(mapArray)
}

不能作为 map 键的类型

以下类型不能作为 map 的键:

最佳实践

小结

在 Go 语言中,只有那些不可变并且可比较的类型才能作为 map 的键。在日常编程中,应该选择合适的键类型以确保 map 的高效和准确性。

以上就是详解Golang中哪些类型可以作为map的key的详细内容,更多关于Golang作为map的key的类型的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文