MOCKSTACKS
EN
Questions And Answers

More Tutorials








Go Maps

One of the most useful data structures in computer science is the hash table. Many hash table implementations exist with varying properties, but in general they offer fast lookups, adds, and deletes. Go provides a built-in map type that implements a hash table.

To create an empty map, use the builtin make:

make(map[key-type]val-type)
.

Example Of Go Map

package main
import "fmt"

func main() {

    my_map := make(map[string]int)

    my_map["key_1"] = 22
    my_map["key_2"] = 33

    fmt.Println("my_map: ", my_map)
}

Output

my_map: map[key_1:22 key_2:33]


Access an element in Go Map

Get a value for a key with name[key].

package main
import "fmt"

func main() {

    my_map := make(map[string]int)

    my_map["key_1"] = 22
    my_map["key_2"] = 33

    fmt.Println("my_value: ", my_map["key_1"])
}

Output

my_value: 22


Delete an Element Of Go Map

The builtin delete() function removes key/value pairs from a map.

package main
import "fmt"

func main() {

    my_map := make(map[string]int)

    my_map["key_1"] = 22
    my_map["key_2"] = 33

    delete(my_map, "key_2")

    fmt.Println("my_map: ", my_map)
}

Output

my_map: map[key_1:22]


Check Element exist in Go Map

The builtin function _, is used to identify if an element exist in a map.

package main
import "fmt"

func main() {

    my_map := make(map[string]int)

    my_map["key_1"] = 22
    my_map["key_2"] = 33

    _, keyExist_K_3 := my_map["key_3"]
    _, keyExist_K_2 := my_map["key_2"]

    fmt.Println("Element Key 2 exist: ", keyExist_K_2)
    fmt.Println("Element Key 3 exist: ", keyExist_K_3)

}

Output

Element Key 2 exist: true
Element Key 3 exist: false

Conclusion

In this page (written and validated by ) you learned about Go Maps . What's Next? If you are interested in completing Go tutorial, your next topic will be learning about: Go If..else..else if.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.