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.

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

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序