csdnceshi52
妄徒之命
采纳率25%
2012-04-11 12:30

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

已采纳
i := 123
s := string(i) 

s is 'E', but what I want is "123"

Please tell me how can I get "123".

And in Java, I can do in this way:

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

how can I concat two strings in Go?

转载于:https://stackoverflow.com/questions/10105935/how-to-convert-an-int-value-to-string-in-go

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

7条回答

  • weixin_41568126 乱世@小熊 9年前

    Use the strconv package's Itoa function.

    For example:

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

    You can concat strings simply by +'ing them, or by using the Join function of the strings package.

    点赞 21 评论 复制链接分享
  • csdnceshi77 狐狸.fox 7年前
    fmt.Sprintf("%v",value);
    

    If you know the specific type of value use the corresponding formatter for example %d for int

    More info - fmt

    点赞 26 评论 复制链接分享
  • weixin_41568131 10.24 5年前

    In this case both strconv and fmt.Sprintf do the same job but using the strconv package's Itoa function is the best choice, because fmt.Sprintf allocate one more object during conversion.

    check the nenchmark result of both check the benchmark here: https://gist.github.com/evalphobia/caee1602969a640a4530

    see https://play.golang.org/p/hlaz_rMa0D for example.

    点赞 8 评论 复制链接分享
  • weixin_41568127 ?yb? 6年前

    It is interesting to note that strconv.Itoa is shorthand for

    func FormatInt(i int64, base int) string
    

    with base 10

    For Example:

    strconv.Itoa(123)
    

    is equivalent to

    strconv.FormatInt(int64(123), 10)
    
    点赞 3 评论 复制链接分享
  • csdnceshi65 larry*wei 9年前

    You can use fmt.Sprintf

    See http://play.golang.org/p/bXb1vjYbyc for example.

    点赞 3 评论 复制链接分享
  • weixin_41568126 乱世@小熊 5年前

    fmt.Sprintf, strconv.Itoa and strconv.FormatInt will do the job. But Sprintf will use the package reflect, and it will allocate one more object, so it's not a good choice.

    enter image description here

    点赞 1 评论 复制链接分享
  • csdnceshi77 狐狸.fox 3年前

    Converting int64:

    n := int64(32)
    str := strconv.FormatInt(n, 10)
    
    fmt.Println(str)
    // Prints "32"
    
    点赞 评论 复制链接分享

相关推荐