panic_defer_convint.go 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // panic_defer_convint.go
  2. package main
  3. import (
  4. "fmt"
  5. "math"
  6. )
  7. func main() {
  8. l := int64(15000)
  9. if i, err := IntFromInt64(l); err != nil {
  10. fmt.Printf("The conversion of %d to an int32 resulted in an error: %s", l, err.Error())
  11. } else {
  12. fmt.Printf("%d converted to an int32 is %d", l, i)
  13. }
  14. fmt.Println()
  15. l = int64(math.MaxInt32 + 15000)
  16. if i, err := IntFromInt64(l); err != nil {
  17. fmt.Printf("The conversion of %d to an int32 resulted in an error: %s", l, err.Error())
  18. } else {
  19. fmt.Printf("%d converted to an int32 is %d", l, i)
  20. }
  21. }
  22. func ConvertInt64ToInt(l int64) int {
  23. if math.MinInt32 <= l && l <= math.MaxInt32 {
  24. return int(l)
  25. }
  26. panic(fmt.Sprintf("%d is out of the int32 range", l))
  27. }
  28. func IntFromInt64(l int64) (i int, err error) {
  29. defer func() {
  30. if e := recover(); e != nil {
  31. err = fmt.Errorf("%v", e)
  32. }
  33. }()
  34. i = ConvertInt64ToInt(l)
  35. return i, nil
  36. }
  37. /* Output:
  38. 15000 converted to an int32 is 15000
  39. The conversion of 2147498647 to an int32 resulted in an error: 2147498647 is out of the int32 range
  40. */