我真的认为这会很简单:
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()
}
请阅读下面的句子。这不是重复的Go 中如何将 int 值转换为字符串?- 因为 :
我知道诸如 strconv.Itoa 函数之类的东西,但它似乎只适用于“常规”整数。它不支持 int16
您可以使用strconv.Itoa (or strconv.FormatInt如果性能至关重要)通过简单地转换int16
to an int
or 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)
}
}
Run as $ 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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)