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>