forked from unknwon/the-way-to-go_ZH_CN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpanic_defer_convint.go
executable file
·45 lines (40 loc) · 1.02 KB
/
panic_defer_convint.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// panic_defer_convint.go
package main
import (
"fmt"
"math"
)
func main() {
l := int64(15000)
if i, err := IntFromInt64(l); err != nil {
fmt.Printf("The conversion of %d to an int32 resulted in an error: %s", l, err.Error())
} else {
fmt.Printf("%d converted to an int32 is %d", l, i)
}
fmt.Println()
l = int64(math.MaxInt32 + 15000)
if i, err := IntFromInt64(l); err != nil {
fmt.Printf("The conversion of %d to an int32 resulted in an error: %s", l, err.Error())
} else {
fmt.Printf("%d converted to an int32 is %d", l, i)
}
}
func ConvertInt64ToInt(l int64) int {
if math.MinInt32 <= l && l <= math.MaxInt32 {
return int(l)
}
panic(fmt.Sprintf("%d is out of the int32 range", l))
}
func IntFromInt64(l int64) (i int, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
}
}()
i = ConvertInt64ToInt(l)
return i, nil
}
/* Output:
15000 converted to an int32 is 15000
The conversion of 2147498647 to an int32 resulted in an error: 2147498647 is out of the int32 range
*/