go - Int 串进去?

标签 go

<分区>

我真的以为这会很简单:

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

最佳答案

您可以使用 strconv.Itoa (或 strconv.FormatInt,如果性能很重要)只需将 int16 转换为 intint64,例如 ( 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

关于go - Int 串进去?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51969470/

相关文章:

postgresql - 在 postgreSQL 中使用主键

go - 使用struct解析JSON

go - 在 Golang iris 上的某个点停止请求执行

高语 : Semantic Meaning of a Property Wrapped in Parenthesis?

go - 源代码缺少函数体,如何编译?

postgresql - DefaultServeMux 中的 SQL 给出错误

c - 转到 []string 到 C char**

c++ - Go是否支持调用C++函数?

go - 如何在被测函数内创建模拟

Golang检查字符串是否是有效路径