-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathint.go
41 lines (34 loc) · 818 Bytes
/
int.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
package g
import (
"errors"
"fmt"
"strconv"
)
// StringToInt converts a string to an integer.
// If the conversion fails and a default value is provided, it
// returns the default value. Otherwise, it returns an error.
//
// Example Usage:
//
// i, err := StringToInt("41") // 41, nil
// i, err := StringToInt("abc", 7) // 7, error
func StringToInt(v string, def ...int) (int, error) {
var d int = 0
if len(def) > 0 {
d = def[0]
}
if v == "" {
return d, errors.New("empty string and no default value")
}
i, err := strconv.Atoi(v)
if err != nil {
return d, err
}
return i, nil
}
// IntToString converts an integer to a string.
// It handles different integer types such as int, int64, int32,
// uint, uint64,uint32, etc.
func IntToString[T Integer](v T) string {
return fmt.Sprintf("%v", v)
}