How to convert int64 to int in Go?

In Go, what is the best strategy for converting int64 to int ? I have difficulty comparing two

 package main import ( "math" "strings" "strconv" ) type largestPrimeFactor struct { N int Result int } func main() { base := largestPrimeFactor{N:13195} max := math.Sqrt(float64(base.N)) maxStr := strconv.FormatFloat(max, 'E', 'G', 64) maxShift := strings.Split(maxStr, ".")[0] maxInt, err := strconv.ParseInt(maxShift, 10, 64) if (err != nil) { panic(err) } 

on the next line

  for a := 2; a < maxInt; a++ { if isPrime(a) { if base.N % a == 0 { base.Result = a } } } println(base) } func isPrime(n int) bool { flag := false max := math.Sqrt(float64(n)) maxStr := strconv.FormatFloat(max, 'E', 'G', 64) maxShift := strings.Split(maxStr, ".")[0] maxInt, err := strconv.ParseInt(maxShift, 10, 64) if (err != nil) { panic(err) } for a := 2; a < maxInt; a++ { if (n % a == 0) { flag := true } } return flag } 
+5
source share
1 answer

You convert them with type "conversion"

 var a int var b int64 int64(a) < b 

When comparing values, you always want to convert a smaller type to a larger one. Converting the other path will probably truncate the value:

 var x int32 = 0 var y int64 = math.MaxInt32 + 1 // y == 2147483648 if x < int32(y) { // this evaluates to false, because int32(y) is -2147483648 

Or in your case, to convert the value of maxInt int64 to int , you can use

 for a := 2; a < int(maxInt); a++ { 

which could not execute correctly if maxInt overflows the maximum value of type int on your system.

+11
source

All Articles