Go 語言中將整數變數轉換為字串的不同方法


在 Go 中,將整數變數轉換為字串可以透過多種方式實現。可以使用內建函式和包來完成此任務。本文將探討在 Go 中將整數變數轉換為字串的不同方法。

strconv.Itoa() 函式

strconv 包提供了一個名為 Itoa() 的函式,用於將整數轉換為其字串表示形式。此函式以整數作為引數,並返回其字串表示形式。

示例

package main

import (
   "fmt"
   "strconv"
)

func main() {
   num := 123
   str := strconv.Itoa(num)
   fmt.Printf("Type: %T, Value: %s\n", str, str)
}

輸出

Type: string, Value: 123

fmt.Sprintf() 函式

Go 中的 fmt 包提供了一個名為 Sprintf() 的函式,用於格式化字串。它也用於將整數變數轉換為字串。此函式以格式字串和值列表作為引數,並返回格式化的字串。

示例

package main

import (
   "fmt"
)

func main() {
   num := 123
   str := fmt.Sprintf("%d", num)
   fmt.Printf("Type: %T, Value: %s\n", str, str)
}

輸出

Type: string, Value: 123

strconv.FormatInt() 函式

strconv 包提供另一個名為 FormatInt() 的函式,用於將整數變數轉換為字串。此函式接受兩個引數:整數值和數字系統的基數。

示例

package main

import (
   "fmt"
   "strconv"
)

func main() {
   num := int64(123)
   str := strconv.FormatInt(num, 10)
   fmt.Printf("Type: %T, Value: %s\n", str, str)
}

輸出

Type: string, Value: 123

strconv.FormatUint() 函式

與上一個函式類似,strconv 包提供另一個名為 FormatUint() 的函式,用於將無符號整數變數轉換為字串。此函式也接受兩個引數:無符號整數值和數字系統的基數。

示例

package main

import (
   "fmt"
   "strconv"
)

func main() {
   num := uint64(123)
   str := strconv.FormatUint(num, 10)
   fmt.Printf("Type: %T, Value: %s\n", str, str)
}

輸出

Type: string, Value: 123

結論

在 Go 中,可以使用各種內建函式和包將整數變數轉換為字串。最常用的函式是 strconv.Itoa() 和 fmt.Sprintf()。這些函式提供了一種簡單的方法來將整數變數轉換為其字串表示形式。strconv 包還提供 FormatInt() 和 FormatUint() 函式,分別用於將整數和無符號整數轉換為字串。

更新於: 2023年4月12日

575 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.