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

问题描述 投票:400回答:9
i := 123
s := string(i) 

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

请告诉我如何获得“123”。

在Java中,我可以这样做:

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

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

string go int converters
9个回答
684
投票

使用strconv包的Itoa函数。

例如:

package main

import (
    "strconv"
    "fmt"
)

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

你可以简单地通过+'ing它们,或者使用Join包的strings函数来连接字符串。


127
投票
fmt.Sprintf("%v",value);

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

更多信息 - fmt


43
投票

有趣的是,strconv.Itoashorthand

func FormatInt(i int64, base int) string

基地10

例如:

strconv.Itoa(123)

相当于

strconv.FormatInt(int64(123), 10)

36
投票

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

enter image description here


34
投票

你可以使用fmt.Sprintf

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


21
投票

在这种情况下,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为例。


6
投票

转换int64

n := int64(32)
str := strconv.FormatInt(n, 10)

fmt.Println(str)
// Prints "32"

1
投票

好吧,他们中的大多数都向你展示了一些好的东西我们给你这个:

// ToString Change arg to string
func ToString(arg interface{}, timeFormat ...string) string {
    if len(timeFormat) > 1 {
        log.SetFlags(log.Llongfile | log.LstdFlags)
        log.Println(errors.New(fmt.Sprintf("timeFormat's length should be one")))
    }
    var tmp = reflect.Indirect(reflect.ValueOf(arg)).Interface()
    switch v := tmp.(type) {
    case int:
        return strconv.Itoa(v)
    case int8:
        return strconv.FormatInt(int64(v), 10)
    case int16:
        return strconv.FormatInt(int64(v), 10)
    case int32:
        return strconv.FormatInt(int64(v), 10)
    case int64:
        return strconv.FormatInt(v, 10)
    case string:
        return v
    case float32:
        return strconv.FormatFloat(float64(v), 'f', -1, 32)
    case float64:
        return strconv.FormatFloat(v, 'f', -1, 64)
    case time.Time:
        if len(timeFormat) == 1 {
            return v.Format(timeFormat[0])
        }
        return v.Format("2006-01-02 15:04:05")
    case jsoncrack.Time:
        if len(timeFormat) == 1 {
            return v.Time().Format(timeFormat[0])
        }
        return v.Time().Format("2006-01-02 15:04:05")
    case fmt.Stringer:
        return v.String()
    case reflect.Value:
        return ToString(v.Interface(), timeFormat...)
    default:
        return ""
    }
}

0
投票
package main

import (
    "fmt" 
    "strconv"
)

func main(){
//First question: how to get int string?

    intValue := 123
    // keeping it in separate variable : 
    strValue := strconv.Itoa(intValue) 
    fmt.Println(strValue)

//Second question: how to concat two strings?

    firstStr := "ab"
    secondStr := "c"
    s := firstStr + secondStr
    fmt.Println(s)
}
© www.soinside.com 2019 - 2024. All rights reserved.