首页 文章

如何在Go中将int值转换为字符串?

提问于
浏览
350
i := 123
s := string(i)

s是'E',但我想要的是“123”

请告诉我怎样才能得到“123” .

在Java中,我可以这样做:

String s = "ab" + "c"  // s is "abc"

怎么能在Go中使用 concat 两个字符串?

7 回答

  • 29

    使用strconv包的 Itoa 函数 .

    例如:

    package main
    
    import (
        "strconv"
        "fmt"
    )
    
    func main() {
        t := strconv.Itoa(123)
        fmt.Println(t)
    }
    

    您可以简单地通过 + 或者使用strings包的 Join 函数来连接字符串 .

  • 547
    fmt.Sprintf("%v",value);
    

    如果您知道特定类型的值,请使用相应的格式化程序,例如 %d for int

    更多信息 - fmt

  • 35

    你可以用fmt.Sprintf

    例如,请参见http://play.golang.org/p/bXb1vjYbyc .

  • 109

    值得注意的是 strconv.Itoashorthand

    func FormatInt(i int64, base int) string
    

    基地10

    例如:

    strconv.Itoa(123)
    

    相当于

    strconv.FormatInt(int64(123), 10)
    
  • 1

    fmt.Sprintfstrconv.Itoastrconv.FormatInt 将完成这项工作 . 但 Sprintf 将使用包 reflect ,它将再分配一个对象,因此它不是一个好的选择 .

    enter image description here

  • 15

    在这种情况下, strconvfmt.Sprintf 都执行相同的工作,但使用 strconv 包的 Itoa 函数是最佳选择,因为 fmt.Sprintf 在转换期间再分配一个对象 .

    check the nenchmark result of both
    在这里检查基准:https://gist.github.com/evalphobia/caee1602969a640a4530

    例如,见https://play.golang.org/p/hlaz_rMa0D .

  • 35

    转换 int64

    n := int64(32)
    str := strconv.FormatInt(n, 10)
    
    fmt.Println(str)
    // Prints "32"
    

相关问题