From 651ed840ca11e63ac840c4b8e00e877a0905a128 Mon Sep 17 00:00:00 2001 From: Chin-Ya Huang Date: Thu, 25 Apr 2024 12:12:22 +0800 Subject: [PATCH] feat(misc): convert given value to string Signed-off-by: Chin-Ya Huang --- utils/misc.go | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/utils/misc.go b/utils/misc.go index 8eeb4177..fd446208 100644 --- a/utils/misc.go +++ b/utils/misc.go @@ -2,10 +2,12 @@ package utils import ( "crypto/rand" + "fmt" "math/big" "path/filepath" "reflect" "runtime" + "strconv" "github.com/google/uuid" "github.com/pkg/errors" @@ -98,3 +100,21 @@ func GenerateRandomNumber(lower, upper int64) (int64, error) { } return (lower + randNum.Int64()), nil } + +// ConvertTypeToString converts the given value to string. +func ConvertTypeToString[T any](value T) string { + v := reflect.ValueOf(value) + + switch v.Kind() { + case reflect.String: + return v.String() + case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: + return strconv.FormatInt(v.Int(), 10) + case reflect.Float32, reflect.Float64: + return strconv.FormatFloat(v.Float(), 'f', -1, 64) + case reflect.Bool: + return strconv.FormatBool(v.Bool()) + default: + return fmt.Sprintf("Unsupported type: %v", v.Kind()) + } +}