想要串入int吗? [重复]

想要串入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>

此问题已经存在 在这里有一个答案: p>

  • 如何在Go中将int值转换为字符串? 9个答案 span> li> ul> div>

    我真的认为这很简单 : p>

      string(myInt)
      code>  pre> 
     
     

    它似乎没有。 p>

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

      func(xis * Int16Slice)ConvertToStringWithSeparator(分隔符字符串)字符串{
     var缓冲区字节。i的缓冲区
    ,值:= range * xis  {
     buffer.WriteString(string(value))
     if i!= len(* xis)-1 {
     buffer.WriteString(separator)
    } 
    } 
    返回buffer.String()
      } 
      code>  pre> 
     
     

    请阅读以下句子。 这不是如何在Go中将int值转换为字符串吗?-因为: 我知道类似 strconv.Itoa函数,但似乎只能在“常规” int上使用。 它不支持int16 p> div>

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

you can use Sprintf:

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

or Itoa

str := strconv.Itoa(3)

You can convert the int16 to int and then use the strconv.Itoa function to convert int16 to string.

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