# 如何在 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.