我真的以为这会很简单:
string(myInt)
看来不是。
我正在编写一个函数,它接受一片整数,并将每个整数附加到一个字符串 - 并在每个整数之间添加一个分隔符。这是我的代码。
func(xis *Int16Slice) ConvertToStringWithSeparator(separator string) string{
var buffer bytes.Buffer
for i, value := range *xis{
buffer.WriteString(string(value))
if i != len(*xis) -1 {
buffer.WriteString(separator)
}
}
return buffer.String()
}
请阅读下面的句子。这不是 How to convert an int value to string in Go? 的副本- 因为 :
我知道 strconv.Itoa 函数之类的东西,但它似乎只适用于“常规”整数。它不支持 int16
您可以使用 strconv.Itoa
(或 strconv.FormatInt
,如果性能很重要)只需将 int16
转换为 int
或 int64
,例如 ( Go Playground ):
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