2018-09-07 14:09
浏览 136


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


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]

yields an additional untyped boolean value.

I am still learning Go. Is it a "syntax feature" that is baked into a language and "just works when this syntax is used", i.e. calls to v := a[x] and v, ok := a[x] are represented as different types of nodes in AST like MapGetAndCheckExistsNode(m, k, v, ok) vs MapGet(m, k, v)? Or this is implemented using "normal" Go syntax and indexing function is somehow aware of whether it's output is later "destructured" or not? Is it possible to force index expression to return tuple or struct with s.v and s.ok fields using s := a[x] syntax?

图片转代码服务由CSDN问答提供 功能建议

如果地图包含带有键x的条目,则a [x]是具有以下内容的地图元素 键x和a [x]的类型是M

的元素类型 分配 或特殊形式的初始化中使用的map [K] V类型的map a上的索引表达式

v,好的:= a [x] < / code>

产生一个附加的 无类型布尔值。

我仍在学习Go。 它是否是一种“语法功能”,已被翻译成一种语言并且“仅在使用此语法时才起作用”,即调用 v:= a [x] v,确定:= a [x] 在AST中表示为不同类型的节点,例如 MapGetAndCheckExistsNode(m,k,v,ok) vs MapGet(m,k,v)? 还是使用“常规” Go语法实现此功能,索引功能以某种方式知道其输出是否以后会“解构”? 是否可以使用 s:= a [x] 语法强制索引表达式返回带有 sv s.ok 字段的元组或结构?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongzhang2150 2018-09-07 21:15

    It’s an arbitrary rule as part of the language itself. It is used to avoid panics on typecasts:

    t, ok := x.(T)  

    Or to check if a key really exists in a map:

    v, ok := m[k]

    Or to check a receive worked:

    x, ok := <-ch

    It’s not possible to do it with your own functions, only in these special cases inserted by the language designers. See the spec for more.

    解决 无用
    打赏 举报

相关推荐 更多相似问题