Int 串进去?

我真的认为这会很简单:


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



绝地无双
浏览 104回答 2
2回答

幕布斯6054654

您可以通过简单地将 the 转换为or来使用strconv.Itoa(或者strconv.FormatInt如果性能至关重要),例如(Go Playground):int16intint64x := uint16(123)strconv.Itoa(int(x))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // => "123"strconv.FormatInt(int64(x), 10) // => "123"strconv.FormatInt(...)请注意,根据一个简单的基准测试,它可能会稍微快一些:// itoa_test.gopackage mainimport (&nbsp; "strconv"&nbsp; "testing")const x = int16(123)func Benchmark_Itoa(b *testing.B) {&nbsp; for i := 0; i < b.N; i++ {&nbsp; &nbsp; strconv.Itoa(int(x))&nbsp; }}func Benchmark_FormatInt(b *testing.B) {&nbsp; for i := 0; i < b.N; i++ {&nbsp; &nbsp; strconv.FormatInt(int64(x), 10)&nbsp; }}运行为$ go test -bench=. ./itoa_test.go:goos: darwingoarch: amd64Benchmark_Itoa-8&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 50000000&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 30.3 ns/opBenchmark_FormatInt-8&nbsp; &nbsp; &nbsp; &nbsp;50000000&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 27.8 ns/opPASSok&nbsp; &nbsp; &nbsp; command-line-arguments&nbsp; 2.976s

慕的地10843

你可以使用 Sprintf:&nbsp; num := 33&nbsp; str := fmt.Sprintf("%d", num)&nbsp; fmt.Println(str)或淹死str := strconv.Itoa(3)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go