har*_*ass 447 string int go converters
i := 123
s := string(i)
Run Code Online (Sandbox Code Playgroud)
s是'E',但我想要的是"123"
请告诉我如何获得"123".
在Java中,我可以这样做:
String s = "ab" + "c" // s is "abc"
Run Code Online (Sandbox Code Playgroud)
我怎么能concat
在Go中使用两个字符串?
Kla*_*sen 706
使用strconv
包的Itoa
功能.
例如:
package main
import (
"strconv"
"fmt"
)
func main() {
t := strconv.Itoa(123)
fmt.Println(t)
}
Run Code Online (Sandbox Code Playgroud)
您可以简单地通过+
它们或使用包的Join
功能来连接字符串strings
.
Jas*_*ngh 133
fmt.Sprintf("%v",value);
Run Code Online (Sandbox Code Playgroud)
如果你知道值的具体类型使用相应的格式,例如%d
用于int
更多信息 - fmt
kgt*_*eat 44
有趣的是,要注意strconv.Itoa
是速记的
func FormatInt(i int64, base int) string
Run Code Online (Sandbox Code Playgroud)
基地10
例如:
strconv.Itoa(123)
Run Code Online (Sandbox Code Playgroud)
相当于
strconv.FormatInt(int64(123), 10)
Run Code Online (Sandbox Code Playgroud)
Bry*_*yce 37
fmt.Sprintf
,strconv.Itoa
并且strconv.FormatInt
将做的工作.但是Sprintf
会使用这个包reflect
,它会再分配一个对象,所以它不是一个好的选择.
man*_*and 21
在这种情况下,两个strconv
与fmt.Sprintf
做同样的工作,但使用该strconv
软件包的Itoa
功能是最好的选择,因为fmt.Sprintf
在转换过程中分配一个多个对象.
在这里检查基准:https://gist.github.com/evalphobia/caee1602969a640a4530
例如,请参阅https://play.golang.org/p/hlaz_rMa0D.
小智 13
另外一个选择:
package main
import "fmt"
func main() {
n := 123
s := fmt.Sprint(n)
fmt.Println(s == "123")
}
Run Code Online (Sandbox Code Playgroud)
https://golang.org/pkg/fmt#Sprint
转换int64
:
n := int64(32)
str := strconv.FormatInt(n, 10)
fmt.Println(str)
// Prints "32"
Run Code Online (Sandbox Code Playgroud)
小智 5
好的,他们中的大多数都向你展示了一些好东西。让我给你这个:
// 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 ""
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
325217 次 |
最近记录: |