2013-07-15 89 views

回答

3

您可以使用strconv.Atoi,其以您想要的方式包裝strconv.ParseInt

+0

謝謝 - 錯過了它在文檔中。 –

0

使用strconv.ParseIntbitSize parameter

package main 

import (
     "fmt" 
     "strconv" 
) 

// 32 or 64 depending on platform 
const IntBits = 1 << (^uint(0)>>32&1 + ^uint(0)>>16&1 + ^uint(0)>>8&1 + 3) 

func printInt(i int) { 
     fmt.Println(i) 
} 

func main() { 
     s := "-123123112323231231" 
     i64, err := strconv.ParseInt(s, 10, IntBits) 
     if err != nil { 
       fmt.Println("parsing failed for ", s) 
     } 
     i := int(i64) 
     printInt(i) 

     i64, err = strconv.ParseInt(s, 10, 32) 
     if err != nil { 
       fmt.Println("parsing failed for ", s) 
     } 
     i = int(i64) 
     printInt(i) 
} 

Playground


輸出

-123123112323231231 
parsing failed for -123123112323231231 
-2147483648 
+0

這與我已經做的很接近,我想......我只是試圖避免'i64,err:= ...'後面附加'i:= int(i64)'' –