i := 123
s := string(i)
s是'E',但我需要的是"123"。
请告诉我如何获取"123"。
在Java中,我可以这样做:
String s = "ab" + "c" // s is "abc"
如何在Go语言中连接两个字符串?
i := 123
s := string(i)
s是'E',但我需要的是"123"。
请告诉我如何获取"123"。
在Java中,我可以这样做:
String s = "ab" + "c" // s is "abc"
如何在Go语言中连接两个字符串?
有趣的是,strconv.Itoa
是缩写
func FormatInt(i int64, base int) string
使用十进制
例如:
strconv.Itoa(123)
等同于
strconv.FormatInt(int64(123), 10)
package main
import (
"fmt"
)
func main() {
val := 14.7
s := fmt.Sprintf("%f", val)
fmt.Println(s)
}
在这种情况下,strconv
和fmt.Sprintf
都可以完成同样的工作,但是使用strconv
包中的Itoa
函数是最好的选择,因为fmt.Sprintf
在转换过程中会多分配一个对象。
查看基准测试结果:https://gist.github.com/evalphobia/caee1602969a640a4530
fmt.Sprintf
和 strconv.iota
在易用性方面相似,并且上述数据显示 iota 的速度更快,对 GC 的影响更小,因此在需要转换单个整数时,通常应使用 iota
。 - Edward转换 int64
:
n := int64(32)
str := strconv.FormatInt(n, 10)
fmt.Println(str)
// Prints "32"
另一个选择:
package main
import "fmt"
func main() {
n := 123
s := fmt.Sprint(n)
fmt.Println(s == "123")
}
好的,他们中的大多数都向您展示了一些有用的东西。让我给你介绍这个:
// ToString Change arg to string
func ToString(arg interface{}, timeFormat ...string) string {
if len(timeFormat) > 1 {
log.SetFlags(log.Llongfile | log.LstdFlags)
log.Println(errors.New(fmt.Sprintf("timeFormat's length should be one")))
}
var tmp = reflect.Indirect(reflect.ValueOf(arg)).Interface()
switch v := tmp.(type) {
case int:
return strconv.Itoa(v)
case int8:
return strconv.FormatInt(int64(v), 10)
case int16:
return strconv.FormatInt(int64(v), 10)
case int32:
return strconv.FormatInt(int64(v), 10)
case int64:
return strconv.FormatInt(v, 10)
case string:
return v
case float32:
return strconv.FormatFloat(float64(v), 'f', -1, 32)
case float64:
return strconv.FormatFloat(v, 'f', -1, 64)
case time.Time:
if len(timeFormat) == 1 {
return v.Format(timeFormat[0])
}
return v.Format("2006-01-02 15:04:05")
case jsoncrack.Time:
if len(timeFormat) == 1 {
return v.Time().Format(timeFormat[0])
}
return v.Time().Format("2006-01-02 15:04:05")
case fmt.Stringer:
return v.String()
case reflect.Value:
return ToString(v.Interface(), timeFormat...)
default:
return ""
}
}
fmt.Sprint
,它可以做到同样的效果(除了 time.Time
和 jsoncrack.Time
(一个我从未听说过的依赖包)值)。 - dolmenpackage main
import (
"fmt"
"strconv"
)
func main(){
//First question: how to get int string?
intValue := 123
// keeping it in separate variable :
strValue := strconv.Itoa(intValue)
fmt.Println(strValue)
//Second question: how to concat two strings?
firstStr := "ab"
secondStr := "c"
s := firstStr + secondStr
fmt.Println(s)
}
strconv.Itoa(i)
(int转ASCII)将一个整数设置为字符串。请参见https://dev59.com/e2Yr5IYBdhLWcg3w0taE#62737936。`strconv.Atoi(s)`(ASCII转int)将一个字符串设置为整数。请参见https://dev59.com/OVwZ5IYBdhLWcg3waPvX#62740786。 - user12817546