2018-10-27 03:33
浏览 982


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.

图片转代码服务由CSDN问答提供 功能建议


Go中的某些函数返回多个 值(通常是值和错误)。 我写的是一个函子,它返回这些函数之一的返回值,即使很容易将这些值放在变量上并仅返回第一个函数,我也怀疑是否只能在一行中执行相同的操作 没有多余的变量 这是在其他语言(例如C,Java,C#,Ruby等)中经常使用的东西

  func someFunc(参数字符串)int {
 //对字符串进行某些处理, 不是很重要


   func someFunc(参数字符串)int {
结果,_ = strconv.Atoi(param)

在Go中有可能吗? 它被认为是“良好实践”(例如在Java *中)

注意:在有人说该技术不是Java的良好实践之前,请先说明对于该问题并不重要, 但是有些人(例如我工作的公司中的人)鼓励这种风格。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    点赞 打赏 评论

相关推荐 更多相似问题