2 回答

TA贡献1876条经验 获得超7个赞
您可以通过简单地将 the 转换为or来使用strconv.Itoa
(或者strconv.FormatInt
如果性能至关重要),例如(Go Playground):int16
int
int64
x := uint16(123)
strconv.Itoa(int(x)) // => "123"
strconv.FormatInt(int64(x), 10) // => "123"
strconv.FormatInt(...)请注意,根据一个简单的基准测试,它可能会稍微快一些:
// itoa_test.go
package main
import (
"strconv"
"testing"
)
const x = int16(123)
func Benchmark_Itoa(b *testing.B) {
for i := 0; i < b.N; i++ {
strconv.Itoa(int(x))
}
}
func Benchmark_FormatInt(b *testing.B) {
for i := 0; i < b.N; i++ {
strconv.FormatInt(int64(x), 10)
}
}
运行为$ go test -bench=. ./itoa_test.go:
goos: darwin
goarch: amd64
Benchmark_Itoa-8 50000000 30.3 ns/op
Benchmark_FormatInt-8 50000000 27.8 ns/op
PASS
ok command-line-arguments 2.976s

TA贡献1785条经验 获得超8个赞
你可以使用 Sprintf:
num := 33
str := fmt.Sprintf("%d", num)
fmt.Println(str)
或淹死
str := strconv.Itoa(3)
- 2 回答
- 0 关注
- 103 浏览
添加回答
举报