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 關注
- 85 瀏覽
添加回答
舉報