1. 程式人生 > 實用技巧 >【Golang】型別轉換之 cast 包

【Golang】型別轉換之 cast 包

Go語言中cast包實現了基本資料型別和其字串表示的相互轉換。

cast包

cast 包實現了基本資料型別與其字串表示的轉換,在Go中輕鬆安全地從一種型別轉換為另一種型別.

更多函式請檢視官方文件

用法

Cast提供了一些To_____方法。這些方法將始終返回所需的型別。如果提供了不會轉換為該型別的輸入,則將返回該型別的0或nil值

Cast還提供了與To_____E相同的方法。這些返回與To_____方法相同的結果,外加一個附加錯誤,告訴您是否成功轉換。使用這些方法,您可以分辨出輸入何時與零值匹配或轉換失敗與返回零值之間的區別。

string與int型別轉換

這一組函式是我們平時程式設計中用的最多的。

ToString()

ToString()函式用於將非字串型別的整數轉換為字串型別,函式簽名如下。

示例程式碼如下:

cast.ToString("mayonegg")         // "mayonegg"
cast.ToString(8)                  // "8"
cast.ToString(8.31)               // "8.31"
cast.ToString([]byte("one time")) // "one time"
cast.ToString(nil)                // ""

var foo interface{} = "one more time"
cast.ToString(foo)                // "one more time"

ToInt()

ToInt()函式用於將非 int型別資料轉換為對應的int表示,具體的函式簽名如下。

示例程式碼如下:

cast.ToInt(8)                  // 8
cast.ToInt(8.31)               // 8
cast.ToInt("8")                // 8
cast.ToInt(true)               // 1
cast.ToInt(false)              // 0

var eight interface{} = 8
cast.ToInt(eight)              // 8
cast.ToInt(nil)                // 0