# 如何在 Go 中将整型 int 值转换为字符串

Suraj Joshi 2023年12月11日

package main

import "fmt"

func main() {
s := string(97)
fmt.Printf("Value of 97 after conversion : %v\n", s)
}

Value of 97 after conversion : a

## strconv 包中的 Itoa 函数

strconv实现了基本数据类型的字符串表示之间的转换。要将整数转换为字符串，我们使用来自 strconv 包的 Itoa 函数。

package main

import (
"fmt"
"strconv"
)

func main() {
x := 138
fmt.Printf("Datatype of 138 before conversion : %T\n", x)
a := strconv.Itoa(x)
fmt.Printf("Datatype of 138 after conversion : %T\n", a)

fmt.Println("Number: " + a)
}

Datatype of 138 before conversion : int
Datatype of 138 after conversion : string
Number: 138

## 来自 strconv 包的 FormatInt 函数

package main

import (
"fmt"
"strconv"
)

func main() {
var integer_1 int64 = 31
fmt.Printf("Value of integer_1 before conversion : %v\n", integer_1)
fmt.Printf("Datatype of integer_1 before conversion : %T\n", integer_1)

var string_1 string = strconv.FormatInt(integer_1, 10)
fmt.Printf("Value of integer_1 after conversion in base 10: %v\n", string_1)
fmt.Printf("Datatype of integer_1 after conversion in base 10 : %T\n", string_1)

var string_2 string = strconv.FormatInt(integer_1, 16)
fmt.Printf("Value of integer_1 after conversion in base 16 : %v\n", string_2)
fmt.Printf("Datatype of integer_1 after conversion in base 16 : %T\n", string_2)
}

Value of integer_1 before conversion : 31
Datatype of integer_1 before conversion : int64
Value of integer_1 after conversion in base 10: 31
Datatype of integer_1 after conversion in base 10 : string
Value of integer_1 after conversion in base 16 : 1f
Datatype of integer_1 after conversion in base 16 : string

## Go fmt.Sprint 方法

package main

import (
"fmt"
)

func main() {

x := 138
fmt.Printf("Datatype of 138 before conversion : %T\n", x)
a := fmt.Sprint(x)
fmt.Printf("Datatype of 138 after conversion : %T\n", a)

fmt.Println("Number: " + a)
}

Datatype of 138 before conversion : int
Datatype of 138 after conversion : string
Number: 138

Suraj Joshi is a backend software engineer at Matrice.ai.