Go 中的索引表达式是否会根据上下文更改其 return 类型?
Does index expression in Go change its return type based on context?
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.
我还在学习围棋。它是被烘焙成语言的 "syntax feature" 和 "just works when this syntax is used",即对 v := a[x]
和 v, ok := a[x]
的调用在 AST 中表示为不同类型的节点,如 MapGetAndCheckExistsNode(m, k, v, ok)
对比 MapGet(m, k, v)
?或者这是使用 "normal" Go 语法实现的,索引函数以某种方式知道它的输出是否晚于 "destructured"?是否可以使用 s := a[x]
语法将索引表达式强制为 return 元组或具有 s.v
和 s.ok
字段的结构?
作为语言本身的一部分,这是一个任意规则。它用于避免类型转换的恐慌:
t, ok := x.(T)
或者检查映射中是否确实存在键:
v, ok := m[k]
或检查接收是否有效:
x, ok := <-ch
用你自己的函数是做不到的,只有在语言设计者插入的这些特殊情况下。有关更多信息,请参阅 spec。
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.
我还在学习围棋。它是被烘焙成语言的 "syntax feature" 和 "just works when this syntax is used",即对 v := a[x]
和 v, ok := a[x]
的调用在 AST 中表示为不同类型的节点,如 MapGetAndCheckExistsNode(m, k, v, ok)
对比 MapGet(m, k, v)
?或者这是使用 "normal" Go 语法实现的,索引函数以某种方式知道它的输出是否晚于 "destructured"?是否可以使用 s := a[x]
语法将索引表达式强制为 return 元组或具有 s.v
和 s.ok
字段的结构?
作为语言本身的一部分,这是一个任意规则。它用于避免类型转换的恐慌:
t, ok := x.(T)
或者检查映射中是否确实存在键:
v, ok := m[k]
或检查接收是否有效:
x, ok := <-ch
用你自己的函数是做不到的,只有在语言设计者插入的这些特殊情况下。有关更多信息,请参阅 spec。