類型轉換

int 型轉換爲 int8安全

func Uint8FromInt(n int) (uint8, error) ui

{ spa

    if 0 <= n && n <= math.MaxUint8 io

    { // conversion is safe float

        return uint8(n), nil error

    } co

    return 0, fmt.Errorf("%d is out of the uint8 range", n) math

}return

 

//安全地從 float64 轉換爲 int:
func IntFromFloat64(x float64) int {
    if math.MinInt32 <= x && x <= math.MaxInt32 { // x lies in the integer range
        whole, fraction := math.Modf(x)
        if fraction >= 0.5 {
            whole++
        }
        return int(whole)
    }
    panic(fmt.Sprintf("%g is out of the int32 range", x))
}
printf

相關文章
相關標籤/搜索