duanlang1531 2015-02-12 20:21
浏览 31
已采纳

使用正常功能在Golang中返回类似“ ok”的地图

In Go, the following works (note one use of the map has one return, the other has two returns)

package main

import "fmt"

var someMap = map[string]string { "some key": "hello" }

func main() {
    if value, ok := someMap["some key"]; ok {
        fmt.Println(value)
    }

    value := someMap["some key"]
    fmt.Println(value)
}

However, I have no idea how to do this same thing with my own function. Is it possible to have similar behavior with an optional return like map?

For example:

package main

import "fmt"

func Hello() (string, bool) {
    return "hello", true
}

func main() {
    if value, ok := Hello(); ok {
        fmt.Println(value)
    }

    value := Hello()
    fmt.Println(value)
}

Wont compile (due to the error multiple-value Hello() in single-value context) ... is there a way to make this syntax work for the function Hello()?

  • 写回答

2条回答 默认 最新

  • duagfgfn1981 2015-02-12 20:35
    关注

    map is different because it is a built-in type and not a function. The 2 forms of accessing an element of a map is specified by the Go Language Specification: Index Expressions.

    With functions you can't do this. If a function has 2 return values, you have to "expect" both of them or none at all.

    However you are allowed to assign any of the return values to the Blank identifier:

    s, b := Hello()    // Storing both of the return values
    
    s2, _ := Hello()   // Storing only the first
    
    _, b3 := Hello()   // Storing only the second
    

    You can also choose not to store any of the return values:

    Hello()            // Just executing it, but storing none of the return values
    

    Note: you could also assign both of the return values to the blank identifier, although it has no use (other than validating that it has exactly 2 return values):

    _, _ = Hello()     // Storing none of the return values; note the = instead of :=
    

    You can also try these on the Go Playground.

    Helper function

    If you use it many times and you don't want to use the blank identifier, create a helper function which discards the 2nd return value:

    func Hello2() string {
        s, _ := Hello()
        return s
    }
    

    And now you can do:

    value := Hello2()
    fmt.Println(value)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划