duankuai6991 2018-10-27 03:33
浏览 2002
已采纳

仅在golang中返回多个返回值的第一个结果

Absolute newbie question here.

Some functions in Go return more than one value (normally, the value and an error). I was writing a func who return the return value of one of those functions, and even if it is very easy to put the values on variables and return only the first one, I have the doubt if I could do the same in only one line without the extra variable. This is something often uses in other languages like C, Java, C#, Ruby, etc

func someFunc (param string) int {
   // do something with the string, not very important
   return strconv.Atoi(param) 
}

I know this works

func someFunc (param string) int {
   // do something with the string, not very important
   var result int
   result, _ = strconv.Atoi(param)
   return result 
}

It is this possible in Go? It is considered a "good practice" (like in Java*)

Note: Before someone say that this technique is not a good practice in Java, clarify that is not important for the question, but some people (like the ones in the company I work) encourage that style.

  • 写回答

1条回答 默认 最新

  • dpkk8687 2018-10-27 03:48
    关注

    Use a short variable declaration for the shortest code to accomplish this goal:

    func SomeFunc(parm string) int {
        result, _ := strconv.Atoi(param)
        return result
    }
    

    There is no one line solution without introducing a helper function that accepts two arguments and returns the first. One of these helper functions would be needed for each combination of types where you want to ignore a value.

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

报告相同问题?

悬赏问题

  • ¥70 刚刚看到一个人的网站居然是通过cname访问的
  • ¥15 Attributeerror:super object has no attribute '__sklearn_tags__'_'
  • ¥15 逆置单链表输出不完整
  • ¥15 宇视vms-B200-A16@R启动不了,如下图所示,在软件工具搜不到,如何解决?(操作系统-linux)
  • ¥500 寻找一名电子工程师完成pcb主板设计(拒绝AI生成式答案)
  • ¥15 关于#mysql#的问题:UNION ALL(相关搜索:sql语句)
  • ¥15 matlab二位可视化能否针对不同数值范围分开分级?
  • ¥15 已经创建了模拟器但是不能用来运行app 怎么办😭自己搞两天了
  • ¥15 关于#极限编程#的问题,请各位专家解答!
  • ¥20 win11账户锁定时间设为0无法登录