Int64 to Int Conversion in Go: Preventing Errors
In Go, converting int64 to int can be challenging when comparing the two types. This article explores the recommended approach for this conversion to prevent unexpected results.
Conversion to Larger Type
To ensure accuracy, it's best practice to convert the smaller type (in this case, int) to the larger type (int64). This can be achieved using type conversion:
var a int var b int64 int64(a) < b
Truncation Concerns
When comparing values, converting the larger type to the smaller may lead to data loss or truncation. Consider the following example:
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 }
In this scenario, converting int64(y) to int32 results in -2147483648, losing the original value's higher-order bits.
Optimized Conversion for maxInt
For maxInt int64 values, consider using the following conversion:
for a := 2; a < int(maxInt); a++ { // Execute correctly even if maxInt exceeds the maximum value of int }
By converting maxInt to int and using int() to ensure the correct int sub-type is used, overflow issues can be avoided while ensuring the desired comparison.
Conclusion
Approaching int64 to int conversion with careful consideration of type sizes helps prevent errors and ensures accurate comparisons. By adhering to the principle of converting the smaller type to the larger, developers can avoid data loss and obtain reliable results when working with varying numeric types in Go.
以上是如何在 Go 中安全地將 int64 轉換為 int:避免資料遺失和溢出?的詳細內容。更多資訊請關注PHP中文網其他相關文章!