doq70020 2019-01-05 06:56
浏览 57
已采纳

如何解释这种地图语法?

I am going through the following Go Lang Map data structure. I am little confused with the syntax -

//this is fine
countryCapitalMap = make(map[string]string)
/* insert key-value pairs in the map*/
countryCapitalMap["France"] = "Paris"
capital, ok := countryCapitalMap["United States"]

/* print map using keys*/
for country := range countryCapitalMap {
    fmt.Println("Capital of", country, "is", countryCapitalMap[country])
}

Is it that the countryCapitalMap["United States"] returns two return values from the following line

capital, ok := countryCapitalMap["United States"]

Or countryCapitalMap[country] returns single value from the following line

fmt.Println("Capital of", country, "is", countryCapitalMap[country])

How could I decipher this syntax? Is it based on where and which statement the expression is used with?

  • 写回答

1条回答 默认 最新

  • doukuibi9631 2019-01-05 07:27
    关注

    How could I decipher this syntax?

    Read the definition of the syntax.

    A primary expression of the form

    a[x]
    

    denotes the element of the map a indexed by x. The value x is called the index or map key.

    There is a special form of an index expression on a map.

    v, ok = a[x]
    v, ok := a[x]
    var v, ok = a[x]
    

    yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.


    The Go Programming Language Specification

    Index expressions

    A primary expression of the form

    a[x]
    

    denotes the element of the array, pointer to array, slice, string or map a indexed by x. The value x is called the index or map key, respectively.

    For a of map type M:

    • x's type must be assignable to the key type of M

    • if the map contains an entry with key x, a[x] is the map element with key x and the type of a[x] is the element type of M

    • if the map is nil or does not contain such an entry, a[x] is the zero value for the element type of M

    Otherwise a[x] is illegal.

    An index expression on a map a of type map[K]V used in an assignment or initialization of the special form

    v, ok = a[x]
    v, ok := a[x]
    var v, ok = a[x]
    

    yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.


    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件