Go by Example:maps

Source: Internet
Author: User

Maps is the associated data type built into the go language (sometimes called hashes or dicts in other languages).

Package Mainimport "FMT" Func Main () {//Create an empty dictionary can use built-in functions make: "Made (map[key type] value type)" M: = Make (Map[string]int)//Use classic "name[ Key]=value "To set the value for the key m[" k1 "] = 7m[" K2 "] = 13//with the println output dictionary, it will output all of its key values to the FMT. PRINTLN ("Map:", m)//use "Name[key" to get the value of a key. v1: = m["K1"]fmt. Println ("v1:", v1)//The built-in function returns the number of key-value pairs in the dictionary fmt. Println ("Len:", Len (m))//built-in function delete deletes the value corresponding to a key from the dictionary delete (m, "K2") fmt. PRINTLN ("Map:", m)//To get the value according to the key has an optional second return value;//This return value indicates whether the key exists in the dictionary,//If it is true, returns the corresponding value, or FALSE to return a value of 0// Sometimes it is necessary to use this return value to determine whether the return result is a value or a value of 0//For example, the dictionary does not exist key x corresponding integer value, return 0 value is 0, but just the dictionary has//key y corresponds to the value of 0, this time need that optional return value to determine if the value 0. _, OK: = m["K2"]fmt. Println ("OK:", OK)//You can initialize a dictionary with ": =" at the same time as defined n: = map[string]int{"foo": 1, "bar": 2}fmt. PRINTLN ("Map:", N)}

Output

$ go Run maps.go map:map[k1:7 k2:13]v1:  7len:2map:map[k1:7]prs:falsemap:map[foo:1 Bar:2]
when using FMT. PRINTLN Print output dictionary, the output format is: Map[k:v k:v].


To learn more about dictionaries, see Learning Golang Language (7): Type--Dictionary

Next example: Go by Example:range.


English original

Go by Example:maps

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.