代码之家  ›  专栏  ›  技术社区  ›  MickeyThreeSheds

要在go中字符串吗?[副本]

go
  •  0
  • MickeyThreeSheds  · 技术社区  · 8 年前

    我真的认为这很简单:

    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函数之类的东西,但它似乎只对“常规”int起作用。它不支持int16

    3 回复  |  直到 8 年前
        1
  •  5
  •   maerics    8 年前

    你可以用 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
    
        2
  •  3
  •   Or Yaacov    8 年前

    您可以使用Sprintf:

      num := 33
      str := fmt.Sprintf("%d", num)
      fmt.Println(str)
    

    str := strconv.Itoa(3)
    
        3
  •  0
  •   Uttarkar    8 年前

    您可以将int16转换为int,然后使用strconv.Itoa函数将int16转换为字符串。

    https://play.golang.org/p/pToOjqDKEoi