Example10.map (dictionary)

map  is built Go associated data types (referred to in some other languages hash  or dictionary  )

main Package
 Import  " FMT " 
FUNC main () { 
To create an empty map, requires the use of built-in the make: the make (Map [Key -type] Val- type). 

    m: = the make (Map [String] int) 
typical of the make [Key] = Val syntax to set pairs. 

    m [ " K1 " ] =. 7 
    m [ " K2 " ] = 13 is 
used, for example to print a map Println will output all pairs. 

    fmt.Println ( " Map: " , m) 
using the name [key] to obtain a key value 

    V1: = m [ " K1 " ] 
    fmt.Println ( " V1:, V1) 
When a call to the built-in map len, returns the number of key-value 

    fmt.Println ( " len: " , len (m)) 
built on the delete key can be removed from the map a 

    delete (m, " K2 " ) 
    fmt.Println ( " map: " , m) 
when a value from the map, the optional second return value indicates that the key is in the map. This can be used to eliminate the zero key and the key value does not exist, as 0 or "" ambiguity arising. 

    _, Prs: = m [ " K2 " ] 
    fmt.Println ( " prs: " , prs) 
You can use this same line syntax declare and initialize a new map. 

    n-: = Map [String] int { " foo " :. 1,bar": 2}
    fmt.Println("map:", n)
}

Result:

$ go run maps.go 
map: map[k1:7 k2:13]
v1:  7
len: 2
map: map[k1:7]
prs: false
map: map[foo:1 bar:2]

 

Guess you like

Origin www.cnblogs.com/yhleng/p/11726679.html