Go語言程式:將int型別變數轉換為long


在 Go 語言中,long 型別變數不是一個獨立的資料型別,而是從整數資料型別擴充套件而來,用於儲存更大的整數型別。int 資料型別和 long 資料型別的主要區別在於,int 資料型別為 32 位,而 long 資料型別為 64 位。

語法

func typeOf (x interface{})

typeOf() 函式用於獲取任何變數的型別。此函式位於 reflect 包中,它接收要確定其型別的變數作為引數。然後,該函式返回指定變數的型別作為結果。

func ParseInt(s string, base int, bitSize int) (i int64, err error)

ParseInt() 函式位於 strconv 包中,用於從數字的字串表示形式獲取整數值。此函式接收字串值、基值和位大小作為引數,並返回整數值以及錯誤。錯誤變數包含轉換過程中生成的任何錯誤。

func Itoa(x int) string

Itoa() 函式位於 strconv 包中,用於在基數為 10 時獲取整數變數的字串表示形式。該函式接收要獲取其字串等價物的變數作為引數,並返回字串表示形式,我們可以將其儲存並在螢幕上列印。

演算法

  • 步驟 1 − 首先,我們需要匯入 fmt 和 reflect 包。

  • 步驟 2 − 然後,啟動 main() 函式。

  • 步驟 3 − 在 main 函式內部初始化名為 x 的整數資料型別變數,並向其中儲存值。然後使用 fmt.Println() 函式在螢幕上列印該變數。

  • 步驟 4 − 此外,使用 reflect 包中的 TypeOf() 函式列印此變數的型別。

  • 步驟 5 − 現在,為了將此變數轉換為 long,將該變數作為引數傳遞給 int64() 函式,並將結果儲存在相同資料型別的新的變數中。

  • 步驟 6 − 這樣獲得的新變數是 long 型別,並在螢幕上列印此變數中的資料及其型別,使用 TypeOf() 函式。

示例 1

在本例中,我們將使用型別轉換方法將整數資料型別變數轉換為 long。型別轉換透過將變數作為引數傳遞給 int64() 函式來實現。

package main
import (
   "fmt"
   "reflect"
)
func main() {
   var x int = 5
   fmt.Println("The variable to be converted is:", x)
   fmt.Println("Type of x is:", reflect.TypeOf(x))
   fmt.Println()
   var y int64 = int64(x)
   fmt.Println("The variable obtained after converting the above value to long is:", y)
   fmt.Println("Type of y is:", reflect.TypeOf(y))
}

輸出

The variable to be converted is: 5
Type of x is: int

The variable obtained after converting the above value to long is: 5
Type of y is: int64

示例 2

在本例中,我們將使用 strconv 包中的 ParseInt() 函式將整數型別變數轉換為 long。

package main
import (
   "fmt"
   "reflect"
   "strconv"
)
func main() {
   var x int = 51
   fmt.Println("The variable to be converted is:", x)
   fmt.Println("Type of x is:", reflect.TypeOf(x))
   fmt.Println()
   y, _ := strconv.ParseInt(strconv.Itoa(x), 10, 64)
   fmt.Println("The variable obtained after converting the above value to long is:", y)
   fmt.Println("Type of y is:", reflect.TypeOf(y))
}

輸出

The variable to be converted is: 51
Type of x is: int

The variable obtained after converting the above value to long is: 51
Type of y is: int64

結論

我們已成功編譯並執行了一個 Go 語言程式,用於將整數型別變數轉換為 long。這裡我們使用了兩個示例。在第一個示例中,我們使用型別轉換方法,而在第二個示例中,我們使用內部 Go 函式來獲取結果。我們在第二個示例中使用的函式是 Itoa() 和 ParseInt()。

更新於: 2023年2月16日

2K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告