How to convert an int64 to int in Go?

后端 未结 1 2021
名媛妹妹
名媛妹妹 2020-12-30 22:21

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

package main 

import (
             


        
相关标签:
1条回答
  • 2020-12-30 23:13

    You convert them with a type "conversion"

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

    When comparing values, you always want to convert the smaller type to the larger. Converting the other way will possibly 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 maxInt int64 value to an int, you could use

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

    which would fail to execute correctly if maxInt overflows the max value of the int type on your system.

    0 讨论(0)
提交回复
热议问题