go语言中int、int32、int64转string

1. int转string

func TestIntToString(t *testing.T){
    //int转字符串
    var a int
    a = 23
    b := strconv.Itoa(a)
    t.Logf("b=[%s], b type:%s\n", b, reflect.TypeOf(b))
}
//运行结果
=== RUN   TestIntToString
--- PASS: TestIntToString (0.00s)
    typeConversion_test.go:94: b=[23], b type:string

2. int32转string

func TestInt32ToString(t *testing.T){
    //int32转字符串
    var a int32
    a = 23
    b := fmt.Sprint(a)
    t.Logf("b type :%s\n", reflect.TypeOf(b))
}
//运行结果
=== RUN   TestInt32ToString
--- PASS: TestInt32ToString (0.00s)
    typeConversion_test.go:86: b type :string

fmt.Sprint()的参数为interface,可以将任意的类型转为string


3.int64转string

func TestInt64ToString(t *testing.T){
    //int64转字符串
    var a int64
    a = 23
    b := strconv.FormatInt(a, 10)
    t.Logf("b=[%s], b type:%s\n", b, reflect.TypeOf(b))
}
//运行结果
=== RUN   TestInt64ToString
--- PASS: TestInt64ToString (0.00s)
    typeConversion_test.go:102: b=[23], b type:string

函数原型:func FormatInt(i int64, base int) string
参数说明:base为进制数

base为十和十六进制数的区别的举例

//test1, base=10
func TestInt64ToString(t *testing.T){
    //int64转字符串
    var a int64
    a = 0x1e
    b := strconv.FormatInt(a, 10)
    t.Logf("b=[%s], b type:%s\n", b, reflect.TypeOf(b))
}
//运行结果
=== RUN   TestInt64ToString
--- PASS: TestInt64ToString (0.00s)
    typeConversion_test.go:102: b=[30], b type:string

//test2 ,base=16
func TestInt64ToString(t *testing.T){
    //int64转字符串
    var a int64
    a = 0x1e
    b := strconv.FormatInt(a, 16)
    t.Logf("b=[%s], b type:%s\n", b, reflect.TypeOf(b))
}
//运行结果
=== RUN   TestInt64ToString
--- PASS: TestInt64ToString (0.00s)
    typeConversion_test.go:102: b=[1e], b type:string
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容