安全地从 int 型转换为 int8:

    1. func Uint8FromInt(n int) (uint8, error) {
    2. if 0 <= n && n <= math.MaxUint8 { // conversion is safe
    3. return uint8(n), nil
    4. }
    5. return 0, fmt.Errorf("%d is out of the uint8 range", n)
    6. }

    安全地从 float64 转换为 int:

    1. func IntFromFloat64(x float64) int {
    2. if math.MinInt32 <= x && x <= math.MaxInt32 { // x lies in the integer range
    3. whole, fraction := math.Modf(x)
    4. if fraction >= 0.5 {
    5. whole++
    6. }
    7. return int(whole)
    8. }
    9. panic(fmt.Sprintf("%g is out of the int32 range", x))
    10. }