Go Fast Learning-08-map

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Directory

      • Map
        • Create a Map
        • Setter and Getter
        • Size
        • Delete an element
        • Map nesting
        • Check if key exists
        • Traverse

Summary

Create Map,make,setter,getter,size,delete, check the existence of keys, traverse

Map

Create a Map

Define and then initialize

varmap[int]stringmap[int]string{}   //m1 map[]

Using the Make function

Format is

make([keyType]valueType, cap)Capacity can be omitted

varmap[int]stringmake(map[int]string)

Use shorthand

make(map[int]string)

Setter and Getter

Setter

m3[1"a"     //m3 map[1:a]

The "1" Here is a key, not an index

Getter

a := m3[1]b := m3[2]fmt.Println("a"//a afmt.Println("b"//b

Returns NULL when a nonexistent key is obtained

Size

varlen(m3)

Delete an element

delete(m3, 1)fmt.Println("a", a)   //a afmt.Println("m3"//m3 map[]

Map nesting

The Value of a map is another map

varMMap[int]Map[int]string= Make(Map[int]Map[int]string) m[1] = Make(Map[int]string) m[1][1] ="a"Fmt. Println ("M", m)//m Map[1:map[1:a]]Fmt. Println ("m[1]"M[1])//m[1] map[1:a]

Check if key exists

When you use shorthand to return multiple values at the same time, the second parameter that the map returns is a Boolean value that indicates whether the key exists

m3[1"a"m3[2"b"v, exist := m3[3]           //第二个参数为布尔值,表示键是否存在fmt.Println("v", v)         //vfmt.Println("exist"//exist false

Traverse

forrange m3 {    fmt.Println(k, v)}

where k is the key, if you want to ignore the use of K can use the placeholder "_"

//Ignore value  for  k: = range  w {fmt. Print (k)}//ignore key  for  _, V: = range  w {fmt. Print (v)}  
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.