dpnru86024 2018-09-07 14:09
浏览 146
已采纳

Go中的索引表达式是否会根据上下文更改其返回类型?

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

but

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?

  • 写回答

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.

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

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置