2016-10-10 74 views
1

我目前在做朗朗教程,「數字常量」是精確的。示例代碼開始用下面的語句:打印大號

const (
    // Create a huge number by shifting a 1 bit left 100 places. 
    // In other words, the binary number that is 1 followed by 100 zeroes. 
    Big = 1 << 100 
    // Shift it right again 99 places, so we end up with 1<<1, or 2. 
    Small = Big >> 99 
) 

Big顯然是巨大的,我想打印出來,其類型,像這樣:

fmt.Printf("%T", Big) 
fmt.Println(Big) 

不過,我得到以下誤差爲兩條線:

# command-line-arguments ./compile26.go:19: constant 1267650600228229401496703205376 overflows int

我會嘗試鑄造大一些其它類型,如uint64,它與同樣的錯誤溢出,或只是轉換我噸至一個字符串,而是試圖Big.String()我收到以下錯誤時:

Big.String undefined (type int has no field or method String)

看來,它的類型是int,但我不能打印或將其轉換到任何東西,它溢出的所有方法。我如何處理這個數字/對象,以及如何打印?

+3

常量在Go是這恰好是是const _not_正常的變量,它們是不同的。 const的概念只在編譯期間存在,const是任意的(幾乎)精度和大小,並且算術是可能的。當使用const時,它會轉換爲「正確」類型。這種轉換可能會失敗,因爲您的程序格式不正確。沒有(直接,簡單)的方式來打印'Big'。 – Volker

+1

可能的重複[如何執行算術常量?](http://stackoverflow.com/questions/38982278/how-does-go-perform-arithmetic-on-constants) – icza

回答

0

該值大於任何64位數字類型可以容納的值,因此您無法直接操作它。

如果您需要編寫一個只能使用math/big包進行操作的數字常量,則需要將其存儲爲包可以使用的格式。最簡單的辦法可能是使用一臺10線:

https://play.golang.org/p/Mzwox3I2SL

bigNum := "1267650600228229401496703205376" 
b, ok := big.NewInt(0).SetString(bigNum, 10) 
fmt.Println(ok, b) 
// true 1267650600228229401496703205376