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


在Go語言中,long不是一種獨立的資料型別,而是整數資料型別的一個擴充套件,用於儲存更大的整數值。int資料型別和long資料型別的主要區別在於,int資料型別是32位,而long資料型別是64位。這裡我們將學習使用Go語言將long型別變數轉換為int的不同方法。

方法一:使用型別轉換

在這個例子中,我們將使用型別轉換方法將long型別變數轉換為int。型別轉換透過將變數作為引數傳遞給int()函式來實現。

語法

func typeOf (x interface{})

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

演算法

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

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

  • 步驟3 - 在main函式內部初始化名為x的long型別變數,併為其賦值。

  • 步驟4 - 使用fmt.Println()函式在螢幕上列印變數。

  • 步驟5 - 使用reflect包中的TypeOf()函式列印此變數的型別。

  • 步驟6 - 將結果儲存在相同資料型別的新的變數中。

  • 步驟7 - 使用TypeOf()函式在螢幕上列印此變數中的資料及其型別。

示例

使用型別轉換將long型別變數轉換為int的Go語言程式

package main
import (
   "fmt"
   "reflect"
)

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

輸出

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

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

方法二:使用與運算子

在這種方法中,我們將使用與(&&)運算子,透過與運算子將long型別變數轉換為int。&&運算子用於去除long型別變數的額外位。

演算法

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

  • 步驟2 - 然後啟動main()函式,並初始化一個long型別的變數併為其賦值。

  • 步驟3 - 在螢幕上列印變數,並使用&運算子去除long型別的額外位。

  • 步驟4 - 在螢幕上列印結果及其型別。

示例

使用與運算子將long型別變數轉換為int的Go語言程式

package main
import (
   "fmt"
   "reflect"
)

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

輸出

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

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

結論

我們已經成功編譯並執行了一個Go語言程式,該程式使用示例將long型別變數轉換為int。我們這裡使用了兩個程式,第一個程式使用型別轉換方法,我們只需將要轉換的變數作為引數傳遞給int()函式;而在第二個程式中,我們使用了AND運算子來去除long型別變數的額外位。

更新於:2023年2月13日

431 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告