在单个语句中向字符串添加整数值
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?
我想知道如何将整数值添加到类似“ 10”的字符串值中。 我知道我可以先将 但是有什么方法可以在一条语句中完成? p>
string code>转换为
int code>,然后再添加整数后才能将其转换回
string code>。 但是我可以在golang中的单个语句中完成此操作吗? 例如,我可以使用以下多行代码执行此操作: p>
i,err:= strconv.Atoi(“ 10”)
//处理错误
i = i + 5
s:= strconv.Itoa(i)
code> pre>
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 int
s 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>