drjtua5953
2017-09-27 07:04
浏览 100
已采纳

在单个语句中向字符串添加整数值

I was wondering how can I add an integer value to a string value like "10". I know I can accomplish this by converting the string into an int first and then after adding the integer I can convert it back into string. But can I accomplish this in a single statement in golang. For example I can do this with multiple lines like this:

i, err := strconv.Atoi("10")
// handle error
i = i + 5
s := strconv.Itoa(i)

But is there any way that I can accomplish this in a single statement?

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

我想知道如何将整数值添加到类似“ 10”的字符串值中。 我知道我可以先将 string 转换为 int ,然后再添加整数后才能将其转换回 string 。 但是我可以在golang中的单个语句中完成此操作吗? 例如,我可以使用以下多行代码执行此操作:

  i,err:= strconv.Atoi(“ 10”)
 //处理错误
i = i +  5 
s:= strconv.Itoa(i)
   
 
 

但是有什么方法可以在一条语句中完成? < / DIV>

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

1条回答 默认 最新

  • dongshuming7131 2017-09-27 07:09
    已采纳

    There is no ready function in the standard library for what you want to do. And the reason for that is because adding a number to a number available as a string and having the result as another string is (terribly) inefficient.

    The model (memory representation) of the string type does not support adding numbers to it efficiently (not to mention that string values are immutable, a new one has to be created); the memory model of int does support adding efficiently for example (and CPUs also have direct operations for that). No one wants to add ints to numbers stored as string values. If you want to add numbers, have your numbers ready just as that: numbers. When you want to print or transmit, only then convert it to string (if you must).

    But everything becomes a single statement if you have a ready util function for it:

    func add(s string, n int) (string, error) {
        i, err := strconv.Atoi(s)
        if err != nil {
            return "", err
        }
        return strconv.Itoa(i + n), nil
    }
    

    Using it:

    s, err := add("10", 5)
    fmt.Println(s, err)
    

    Output (try it on the Go Playground):

    15 <nil>
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题