nettools/common/convert.go

59 lines
1.4 KiB
Go
Raw Permalink Normal View History

2024-11-12 10:08:08 +00:00
package commonUtils
2024-11-12 08:10:09 +00:00
import (
"strconv"
"strings"
)
// Converts all the types in
func ConvertArr[Tin any, Tout any](in []Tin, convertFunc CovertFunc[Tin, Tout]) (convertedItems []Tout, err error) {
out := make([]Tout, len(in))
for i, item := range in {
outItem, err := convertFunc(item)
if err != nil {
return nil, err
}
out[i] = outItem
}
return out, nil
}
// More modern approach to parsing integers and floats using generics
func MustStr2Int[T Int](str string, base int, bitSize int) T {
int, err := strconv.ParseInt(str, base, bitSize)
if err != nil {
panic("Error while trying to convert string to integer: " + err.Error())
}
return T(int)
}
func Str2Int[T Int](str string, base int, bitSize int) (T, error) {
out, err := strconv.ParseInt(str, base, bitSize)
return T(out), err
}
func MustStr2Float[T Float](str string, bitSize int) T {
out, err := strconv.ParseFloat(str, bitSize)
if err != nil {
panic("Error while trying to convert string to float: " + err.Error())
}
return T(out)
}
func Str2Float[T Float](str string, bitSize int) (T, error) {
out, err := strconv.ParseFloat(str, bitSize)
return T(out), err
}
func Str2Bool(str string) (val bool, ok bool) {
switch strings.ToLower(str) {
case "true", "yes", "y", "t", "1":
return true, true
case "false", "no", "n", "f", "0":
return false, true
default:
return false, false
}
}