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

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

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?

  • 写回答

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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥15 关于超局变量获取查询的问题
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集
  • ¥15 在启动roslaunch时出现如下问题
  • ¥15 汇编语言实现加减法计算器的功能
  • ¥20 关于多单片机模块化的一些问题