ZetCode

Go int 转 string

最后修改时间 2024 年 4 月 11 日

在本文中,我们将展示如何在 Golang 中将整数转换为字符串。

Go int 转 string 转换

整数到字符串的转换是一种类型转换,其中将整数数据类型的实体更改为字符串类型。

在 Go 中,我们可以使用 strconv.FormatIntstrconv.Itoafmt.Sprintf 函数执行 int 到 string 的转换。

strconv 包实现了基本数据类型与其字符串表示形式之间的转换。

Go int 转 string 使用 Itoa

Itoa 是一个便捷函数,用于将整数转换为字符串。

func Itoa(i int) string

Itoa 等同于 FormatInt(int64(i), 10)

int2str.go
package main

import (
    "fmt"
    "strconv"
)

func main() {

    var apples int = 6

    n := strconv.Itoa(apples)
    msg := "There are " + n + " apples"
    fmt.Println(msg)

    fmt.Printf("%T\n", apples)
    fmt.Printf("%T\n", n)
}

在代码示例中,我们将苹果的数量转换为字符串以构建消息。稍后,我们将输出 applesn 变量的类型。

$ go run int2str.go 
There are 6 apples
int
string

Go int 转 string 使用 strconv.FormatInt

strconv.FormatInt 返回给定基数的值的字符串表示形式;其中 2 <= base <= 36。

int2str2.go
package main

import (
    "fmt"
    "strconv"
)

func main() {

    var file_size int64 = 1544466212

    file_size_s := strconv.FormatInt(file_size, 10)

    msg := "The file size is " + file_size_s + " bytes"
    fmt.Println(msg)
}

在代码示例中,我们将类型为 int64file_size 变量使用 strconv.FormatInt 转换为字符串。

$ go run int2str2.go 
The file size is 1544466212 bytes

Go int 转 string 使用 fmt.Sprintf

将整数转换为字符串的另一种方法是使用 fmt.Sprintf 函数。该函数根据格式说明符进行格式化并返回结果字符串。

int2str3.go
package main

import (
    "fmt"
)

func main() {

    var apples int = 6

    msg := fmt.Sprintf("There are %d apples", apples)
    fmt.Println(msg)
}

fmt.Sprintf 格式化一个新字符串;它用整数值替换 %d 说明符。

在本文中,我们展示了如何在 Go 中执行 int 到 string 的转换。

来源

Go strconv 包 - 参考

作者

我叫 Jan Bodnar,是一名充满激情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。至今,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出所有 Go 教程