duanfan1965
2017-11-03 17:39
浏览 41
已采纳

Golang:有没有一种方法可以在一行中修改其中一个多值返回参数?

I am trying something relatively simple in Go - convert a string to integer and then double it:

myInt, _ := strconv.Atoi(args[1])
doubleArg := myInt * 2

Since Atoi() returns two parameters (the integer and err), I am using myInt, _ := to retrieve the value of the integer. I would like to double it (hence the 2nd line) but can't do all in one line:

myInt, _ := strconv.Atoi(args[1]) * 2

gives me:

multiple-value strconv.Atoi() in single-value context

However, from my experience with most other languages it seems like a lot of boilerplate to have to do this in two lines. Is this just a limitation I'll have to deal with, or is there a better way to write my code?

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

我正在Go中尝试相对简单的方法-将字符串转换为整数,然后将其加倍: \ n

  myInt,_:= strconv.Atoi(args [1])
doubleArg:= myInt * 2 
   
 
 

Atoi()返回两个参数(整数和 err ),我正在使用 myInt,_:= 检索整数的值。 我想将其加倍(因此从第二行开始),但不能在一行中全部完成:

  myInt,_:= strconv.Atoi(args [1])  * 2 
   
 
 

给我:

 单值上下文中的多值strconv.Atoi()\  n   
 
 

但是,根据我对大多数其他语言的经验,似乎需要两行代码来做很多样板工作。 这是我必须解决的一个限制,还是有更好的方法编写代码?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongyan7172 2017-11-03 18:53
    已采纳

    Two lines of code is not really that much. But if you have to do the same thing many times in your code, you might as well write your own version of the conversion then multiplication function. This function can do error checking, and the real work.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题