dongzhui2636 2013-11-02 10:56
浏览 26
已采纳

前往:范围或地图返回什么?

Go has very neat multiple return values paradigm. But It looks like v, ok := map[key] and v, k := range m use different mechanism with same notation. Here is a simple example:

func f2() (k, v string) {
    return "Hello", "World"
}

func main(){
    k := f2() // Doesn't work : multiple-value f2() in single-value context

    m := map[string]int{"One": 1}

    // It works
    v, ok := m["One"]

    // How it all work?
    v := m["One"]
    for k := range m {}
}

In above example, k := f2() gives error as f2 returns two values, whereas v, ok := m["One"] and v := m["One"] - both expressions work without any error. Why is that different behavior?

  • 写回答

1条回答 默认 最新

  • drvpvmz16241016 2013-11-02 11:30
    关注

    A fetch from the built in map, using range on a map, array or slice, and also type assertions allows for one or two variables. This is not the case for user defined functions and methods. If a function declares two return values, you must tell what to do with both of them, or ignore both:

    k, _ := f2() // Specify what to do with each returned value
    f2() // Ignoring both
    

    Why? Because the specification says it is so:

    Map (indexed expressions):

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

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

    where the result of the index expression is a pair of values with types (V, bool). In this form, the value of ok is true if the key x is present in the map, and false otherwise. The value of v is the value a[x] as in the single-result form.

    Range (for statement):

    For each iteration, iteration values are produced as follows:

    Range expression: m map[K]V
    1st value: key k K
    2nd value (if 2nd variable is present): m[k] V

    Type assertion:

    For an expression x of interface type and a type T, the primary expression
    x.(T)
    asserts that x is not nil and that the value stored in x is of type T.

    and

    If a type assertion is used in an assignment or initialization of the form
    v, ok = x.(T)
    v, ok := x.(T)
    var v, ok = x.(T)
    the result of the assertion is a pair of values with types (T, bool)

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

报告相同问题?

悬赏问题

  • ¥15 想用@vueuse 把项目动态改成深色主题,localStorge里面的vueuse-color-scheme一开始就给我改成了dark,不知道什么原因(相关搜索:背景颜色)
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥20 白日门传奇少一个启动区服和启动服务器的快捷键,东西都是全的 , 他们说套一个出来就行了 但我就是弄不好,谁看看,
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题