i := 123
s := string(i)
s is 'E', but what I want is "123"
Please tell me how can I get "123".
And in Java, I can do in this way:
String s = "ab" + "c" // s is "abc"
how can I concat
two strings in Go?
转载于:https://stackoverflow.com/questions/10105935/how-to-convert-an-int-value-to-string-in-go
Use the strconv
package's Itoa
function.
For example:
package main
import (
"strconv"
"fmt"
)
func main() {
t := strconv.Itoa(123)
fmt.Println(t)
}
You can concat strings simply by +
'ing them, or by using the Join
function of the strings
package.
You can use fmt.Sprintf
See http://play.golang.org/p/bXb1vjYbyc for example.
fmt.Sprintf("%v",value);
If you know the specific type of value use the corresponding formatter for example %d
for int
More info - fmt
It is interesting to note that strconv.Itoa
is shorthand for
func FormatInt(i int64, base int) string
with base 10
For Example:
strconv.Itoa(123)
is equivalent to
strconv.FormatInt(int64(123), 10)
fmt.Sprintf
, strconv.Itoa
and strconv.FormatInt
will do the job. But Sprintf
will use the package reflect
, and it will allocate one more object, so it's not a good choice.
In this case both strconv
and fmt.Sprintf
do the same job but using the strconv
package's Itoa
function is the best choice, because fmt.Sprintf
allocate one more object during conversion.
check the benchmark here: https://gist.github.com/evalphobia/caee1602969a640a4530
see https://play.golang.org/p/hlaz_rMa0D for example.
Converting int64
:
n := int64(32)
str := strconv.FormatInt(n, 10)
fmt.Println(str)
// Prints "32"