i := 123 s := string(i)
s是'E',但我想要的是“123”
请告诉我怎样才能得到“123” .
在Java中,我可以这样做:
String s = "ab" + "c" // s is "abc"
怎么能在Go中使用 concat 两个字符串?
concat
使用strconv包的 Itoa 函数 .
Itoa
例如:
package main import ( "strconv" "fmt" ) func main() { t := strconv.Itoa(123) fmt.Println(t) }
您可以简单地通过 + 或者使用strings包的 Join 函数来连接字符串 .
+
Join
fmt.Sprintf("%v",value);
如果您知道特定类型的值,请使用相应的格式化程序,例如 %d for int
%d
int
更多信息 - fmt
你可以用fmt.Sprintf
例如,请参见http://play.golang.org/p/bXb1vjYbyc .
值得注意的是 strconv.Itoa 是shorthand
strconv.Itoa
func FormatInt(i int64, base int) string
基地10
strconv.Itoa(123)
相当于
strconv.FormatInt(int64(123), 10)
fmt.Sprintf , strconv.Itoa 和 strconv.FormatInt 将完成这项工作 . 但 Sprintf 将使用包 reflect ,它将再分配一个对象,因此它不是一个好的选择 .
fmt.Sprintf
strconv.FormatInt
Sprintf
reflect
在这种情况下, strconv 和 fmt.Sprintf 都执行相同的工作,但使用 strconv 包的 Itoa 函数是最佳选择,因为 fmt.Sprintf 在转换期间再分配一个对象 .
strconv
在这里检查基准:https://gist.github.com/evalphobia/caee1602969a640a4530
例如,见https://play.golang.org/p/hlaz_rMa0D .
转换 int64 :
int64
n := int64(32) str := strconv.FormatInt(n, 10) fmt.Println(str) // Prints "32"
7 回答
使用strconv包的
Itoa
函数 .例如:
您可以简单地通过
+
或者使用strings包的Join
函数来连接字符串 .如果您知道特定类型的值,请使用相应的格式化程序,例如
%d
forint
更多信息 - fmt
你可以用fmt.Sprintf
例如,请参见http://play.golang.org/p/bXb1vjYbyc .
值得注意的是
strconv.Itoa
是shorthand基地10
例如:
相当于
fmt.Sprintf
,strconv.Itoa
和strconv.FormatInt
将完成这项工作 . 但Sprintf
将使用包reflect
,它将再分配一个对象,因此它不是一个好的选择 .在这种情况下,
strconv
和fmt.Sprintf
都执行相同的工作,但使用strconv
包的Itoa
函数是最佳选择,因为fmt.Sprintf
在转换期间再分配一个对象 .在这里检查基准:https://gist.github.com/evalphobia/caee1602969a640a4530
例如,见https://play.golang.org/p/hlaz_rMa0D .
转换
int64
: