想要串入int吗?

Mic*_*eds 1 go

我真的以为这很简单:

string(myInt)
Run Code Online (Sandbox Code Playgroud)

似乎没有。

我正在编写一个函数,该函数需要一个int切片,并将每个int附加到字符串中,并在每个int之间添加分隔符。这是我的代码。

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()
}
Run Code Online (Sandbox Code Playgroud)

请阅读下面的句子。这不是如何在Go中将int值转换为字符串的重复项-因为:我知道诸如strconv.Itoa函数之类的东西,但似乎只能在“常规” int上使用。它不支持int16

Or *_*cov 5

你可以使用 Sprintf:

  num := 33
  str := fmt.Sprintf("%d", num)
  fmt.Println(str)
Run Code Online (Sandbox Code Playgroud)

或伊托亚

str := strconv.Itoa(3)
Run Code Online (Sandbox Code Playgroud)


mae*_*ics 5

您可以使用strconv.Itoa(或者strconv.FormatInt,如果性能是至关重要的),通过简单地转换int16int或者int64,例如(去游乐场):

x := uint16(123)
strconv.Itoa(int(x))            // => "123"
strconv.FormatInt(int64(x), 10) // => "123"
Run Code Online (Sandbox Code Playgroud)

请注意,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 Code Online (Sandbox Code Playgroud)

运行方式$ 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
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢这个答案。我们需要更多像您这样的人。 (2认同)