Golang Maps

Golang Maps

在Go语言中,Maps是一种强大的、巧妙的、多功能的数据结构。GolangMaps是一个无序的键值对的集合。它被广泛使用,因为它提供了快速的查找和值,可以在键的帮助下进行检索、更新或删除。

  • 它是对哈希表的一种引用。
  • 由于它的引用类型,它的传递成本很低,例如,对于64位机器,它需要8个字节,对于32位机器,它需要4个字节。
  • 在Maps中,一个键必须是唯一的,并且总是在使用 == 运算符或支持 != 运算符的类型中进行比较。因此,大多数内置类型可以作为键,如int、float64、rune、string、可比较的数组和结构、指针等。像切片和不可比较的数组和结构等数据类型,或者不具有可比性的自定义数据类型,不能作为Maps的键使用。
  • 在Maps中,值不像键那样是唯一的,可以是任何类型,如int, float64, rune, string, pointer, reference type, map type,等等。
  • 键的类型和值的类型必须是相同的,同一Maps中不同类型的键和值是不允许的。但是键的类型和值的类型可以不同。
  • Maps也被称为哈希图,哈希表,无序图,字典,或关联数组。
  • 在Maps中,你只能在Maps被初始化时添加值,如果你试图在未初始化的Maps中添加值,那么编译器会抛出一个错误。

如何创建和初始化Maps

在Go语言中,Maps可以通过两种不同的方式创建和初始化。

1.简单: 在这种方法中,你可以不使用 make() 函数来创建和初始化一个Maps。

创建Maps: 你可以使用给定的语法简单地创建一个Maps。

// An Empty map
map[Key_Type]Value_Type{}

// Map with key-value pair
map[Key_Type]Value_Type{key1: value1, ..., keyN: valueN}

例子。

var mymap map[int]string

在Maps中,Maps的零值是nil,一个nilMaps不包含任何键。如果你试图在nilMaps中添加一个键值对,那么编译器将抛出运行时错误。
使用Maps字面初始化Maps: Maps字面是用数据初始化Maps的最简单方法,只需用冒号将键值对分开,最后的尾部冒号是必须的,如果你不使用,那么编译器将给出一个错误。

例子

// Go program to illustrate how to
// create and initialize maps
package main
 
import "fmt"
 
func main() {
 
    // Creating and initializing empty map
    // Using var keyword
    var map_1 map[int]int
 
    // Checking if the map is nil or not
    if map_1 == nil {
     
        fmt.Println("True")
    } else {
     
        fmt.Println("False")
    }
 
    // Creating and initializing a map
    // Using shorthand declaration and
    // using map literals
    map_2 := map[int]string{
     
            90: "Dog",
            91: "Cat",
            92: "Cow",
            93: "Bird",
            94: "Rabbit",
    }
     
    fmt.Println("Map-2: ", map_2)
}

输出

True
Map-2:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]

2.使用make函数: 你也可以使用make()函数创建一个Maps。这个函数是一个内置的函数,在这个方法中,你只需要传递Maps的类型,它将返回一个初始化的Maps。

语法

make(map[Key_Type]Value_Type, initial_Capacity)
make(map[Key_Type]Value_Type)

例子

// Go program to illustrate how to
// create and initialize a map
// Using make() function
package main
 
import "fmt"
 
func main() {
 
    // Creating a map
    // Using make() function
    var My_map = make(map[float64]string)
    fmt.Println(My_map)
 
    // As we already know that make() function
    // always returns a map which is initialized
    // So, we can add values in it
    My_map[1.3] = "Rohit"
    My_map[1.5] = "Sumit"
    fmt.Println(My_map)
}

输出

map[]
map[1.3:Rohit 1.5:Sumit]

重要观点

1.如何在Maps上进行迭代?: 你可以使用range for循环来迭代Maps。这个循环的值可能会有所不同,因为Maps是一个无序的集合。

例子

// Go program to illustrate how
// to iterate the map using for
// rang loop
 
package main
 
import "fmt"
 
// Main function
func main() {
 
    // Creating and initializing a map
    m_a_p := map[int]string{
 
        90: "Dog",
        91: "Cat",
        92: "Cow",
        93: "Bird",
        94: "Rabbit",
    }
 
    // Iterating map using for rang loop
    for id, pet := range m_a_p {
 
        fmt.Println(id, pet)
    }
}

输出

90 Dog
91 Cat
92 Cow
93 Bird
94 Rabbit

2.如何在Maps中添加键值对?: 在Maps中,你可以使用给定的语法在初始化Maps中添加键值对。

map_name[key]=value

在Maps中,如果你试图添加一个已经存在的键,那么它将简单地用新值覆盖或更新该键的值。

例子

// Go program to illustrate how to add
// a key-value pair in the map using
// make() function
package main
 
import "fmt"
 
// Main function
func main() {
 
    // Creating and initializing a map
    m_a_p := map[int]string{
        90: "Dog",
        91: "Cat",
        92: "Cow",
        93: "Bird",
        94: "Rabbit",
    }
 
    fmt.Println("Original map: ", m_a_p)
 
    // Adding new key-value pairs in the map
    m_a_p[95] = "Parrot"
    m_a_p[96] = "Crow"
    fmt.Println("Map after adding new key-value pair:\n", m_a_p)
 
    // Updating values of the map
    m_a_p[91] = "PIG"
    m_a_p[93] = "DONKEY"
    fmt.Println("\nMap after updating values of the map:\n", m_a_p)
}

输出

Original map:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]
Map after adding new key-value pair:
 map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit 95:Parrot 96:Crow]

Map after updating values of the map:
 map[90:Dog 91:PIG 92:Cow 93:DONKEY 94:Rabbit 95:Parrot 96:Crow]

3.如何在Maps中检索与键相关的值? 在Maps中,你可以使用以下语法在键的帮助下检索一个值。

map_name[key]

如果键不存在于给定的Maps中,那么它将返回Maps的零值,也就是nil。如果键存在于给定的Maps中,那么它将返回与该键相关的值。

例子

// Go program to illustrate how to
// retrieve the value of the key
 
package main
 
import "fmt"
 
// Main function
func main() {
 
    // Creating and initializing a map
    m_a_p := map[int]string{
        90: "Dog",
        91: "Cat",
        92: "Cow",
        93: "Bird",
        94: "Rabbit",
    }
    fmt.Println("Original map: ", m_a_p)
 
    // Retrieving values with the help of keys
    value_1 := m_a_p[90]
    value_2 := m_a_p[93]
    fmt.Println("Value of key[90]: ", value_1)
    fmt.Println("Value of key[93]: ", value_2)
}

输出

Original map:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]
Value of key[90]:  Dog
Value of key[93]:  Bird

4.如何检查Maps中的键是否存在?: 在Maps中,你可以使用以下语法检查给定的键是否存在。

// With value
// It will gives the value and check result
value, check_variable_name:= map_name[key]

or

// Without value using the blank identifier
// It will only give check result
_, check_variable_name:= map_name[key]

在这里,如果 check_variable_name 的值为true,意味着该键存在于给定的Maps中,如果check_variable_name 的值为false,意味着该键不存在于给定的Maps中。

例子

// Go program to illustrate how to
// check the key is available or not
 
package main
 
import "fmt"
 
// Main function
func main() {
 
    // Creating and initializing a map
    m_a_p := map[int]string{
        90: "Dog",
        91: "Cat",
        92: "Cow",
        93: "Bird",
        94: "Rabbit",
    }
 
    fmt.Println("Original map: ", m_a_p)
 
    // Checking the key is available
    // or not in the m_a_p map
    pet_name, ok := m_a_p[90]
    fmt.Println("\nKey present or not:", ok)
    fmt.Println("Value:", pet_name)
 
    // Using blank identifier
    _, ok1 := m_a_p[92]
    fmt.Println("\nKey present or not:", ok1)
}

输出

Original map:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]

Key present or not: true
Value: Dog

Key present or not: true

5.如何从Maps中删除键? 在Maps中,你可以使用delete()函数来删除Maps中的键。这是一个内置的函数,不返回任何值,如果键不在给定的Maps中,也不做任何事情。在这个函数中,你只需传递Maps和你想从Maps中删除的键。

语法

delete(map_name, key)

例子

// Go program to illustrate how to delete a key
 
package main
 
import "fmt"
 
// Main function
func main() {
 
    // Creating and initializing a map
    m_a_p := map[int]string{
        90: "Dog",
        91: "Cat",
        92: "Cow",
        93: "Bird",
        94: "Rabbit",
    }
 
    fmt.Println("Original map: ", m_a_p)
 
    // Deleting keys
    // Using delete function
    delete(m_a_p, 90)
    delete(m_a_p, 93)
 
    fmt.Println("Map after deletion: ", m_a_p)
}

输出

Original map:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]
Map after deletion:  map[91:Cat 92:Cow 94:Rabbit]

6.修改Maps: 我们知道,Maps是引用类型的。因此,当我们把一个现有的Maps分配给一个新的变量时,这两个Maps仍然指向同一个底层数据结构。因此,当我们更新一个Maps时,它将反映在另一个Maps上。

例子

// Go program to illustrate the
// modification concept in map
 
package main
 
import "fmt"
 
// Main function
func main() {
 
    // Creating and initializing a map
    m_a_p := map[int]string{
        90: "Dog",
        91: "Cat",
        92: "Cow",
        93: "Bird",
        94: "Rabbit",
    }
    fmt.Println("Original map: ", m_a_p)
 
    // Assigned the map into a new variable
    new_map := m_a_p
 
    // Perform modification in new_map
    new_map[96] = "Parrot"
    new_map[98] = "Pig"
 
    // Display after modification
    fmt.Println("New map: ", new_map)
    fmt.Println("\nModification done in old map:\n", m_a_p)
}

输出

Original map:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit]
New map:  map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit 96:Parrot 98:Pig]

Modification done in old map:
 map[90:Dog 91:Cat 92:Cow 93:Bird 94:Rabbit 96:Parrot 98:Pig]

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程