为了账号安全,请及时绑定邮箱和手机立即绑定

Int 串进去?

Int 串进去?

Go
绝地无双 2023-03-21 17:17:07
我真的认为这会很简单: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()}请阅读下面的句子。这不是如何在 Go 中将 int 值转换为字符串?- 因为:我知道 strconv.Itoa 函数之类的东西,但它似乎只适用于“常规”整数。它不支持 int16
查看完整描述

2 回答

?
幕布斯6054654

TA贡献1876条经验 获得超7个赞

您可以通过简单地将 the 转换为or来使用strconv.Itoa(或者strconv.FormatInt如果性能至关重要),例如(Go Playground):int16intint64

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




查看完整回答
反对 回复 2023-03-21
?
慕的地10843

TA贡献1785条经验 获得超8个赞

你可以使用 Sprintf:


  num := 33

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

  fmt.Println(str)

或淹死


str := strconv.Itoa(3)


查看完整回答
反对 回复 2023-03-21
  • 2 回答
  • 0 关注
  • 103 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号