drk7700 2018-08-22 14:45
浏览 42
已采纳

想要串入int吗? [重复]

This question already has an answer here:

I really thought this would be as simple as :

string(myInt)

It appears not.

I am writing a function which takes a slice of ints, and appends each one to a string - and adds a separator between each one. Here is my code.

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()
}

Please read the sentence below. This is not a duplicate of How to convert an int value to string in Go? - because : I am aware of things like the strconv.Itoa function, but it appears as though that will only work on "regular" ints. It will not support an int16

</div>
  • 写回答

3条回答 默认 最新

  • doubo82706 2018-08-22 15:36
    关注

    You can use strconv.Itoa (or strconv.FormatInt if performance is critical) by simply converting the int16 to an int or int64, for example (Go Playground):

    x := uint16(123)
    strconv.Itoa(int(x))            // => "123"
    strconv.FormatInt(int64(x), 10) // => "123"
    

    Note that strconv.FormatInt(...) may be slightly faster according to a simple benchmark:

    // 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
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改