fix: update GetValueOrDefault util functions to return default value for zero values

This commit is contained in:
Fu Diwei 2024-11-20 07:49:50 +08:00
parent 82807fcc1b
commit a59184ae5f

View File

@ -22,7 +22,7 @@ func GetValueAsString(dict map[string]any, key string) string {
// - defaultValue: 默认值。
//
// 出参:
// - 字典中键对应的值。如果指定键不存在或者值的类型不是字符串,则返回默认值。
// - 字典中键对应的值。如果指定键不存在、值的类型不是字符串或者值为零值,则返回默认值。
func GetValueOrDefaultAsString(dict map[string]any, key string, defaultValue string) string {
if dict == nil {
return defaultValue
@ -30,9 +30,11 @@ func GetValueOrDefaultAsString(dict map[string]any, key string, defaultValue str
if value, ok := dict[key]; ok {
if result, ok := value.(string); ok {
if result != "" {
return result
}
}
}
return defaultValue
}
@ -57,7 +59,7 @@ func GetValueAsInt32(dict map[string]any, key string) int32 {
// - defaultValue: 默认值。
//
// 出参:
// - 字典中键对应的值。如果指定键不存在或者值的类型不是 32 位整数,则返回默认值。
// - 字典中键对应的值。如果指定键不存在、值的类型不是 32 位整数或者值为零值,则返回默认值。
func GetValueOrDefaultAsInt32(dict map[string]any, key string, defaultValue int32) int32 {
if dict == nil {
return defaultValue
@ -65,16 +67,20 @@ func GetValueOrDefaultAsInt32(dict map[string]any, key string, defaultValue int3
if value, ok := dict[key]; ok {
if result, ok := value.(int32); ok {
if result != 0 {
return result
}
}
// 兼容字符串类型的值
if str, ok := value.(string); ok {
if result, err := strconv.ParseInt(str, 10, 32); err == nil {
if result != 0 {
return int32(result)
}
}
}
}
return defaultValue
}
@ -99,7 +105,7 @@ func GetValueAsInt64(dict map[string]any, key string) int64 {
// - defaultValue: 默认值。
//
// 出参:
// - 字典中键对应的值。如果指定键不存在或者值的类型不是 64 位整数,则返回默认值。
// - 字典中键对应的值。如果指定键不存在、值的类型不是 64 位整数或者值为零值,则返回默认值。
func GetValueOrDefaultAsInt64(dict map[string]any, key string, defaultValue int64) int64 {
if dict == nil {
return defaultValue
@ -107,16 +113,20 @@ func GetValueOrDefaultAsInt64(dict map[string]any, key string, defaultValue int6
if value, ok := dict[key]; ok {
if result, ok := value.(int64); ok {
if result != 0 {
return result
}
}
// 兼容字符串类型的值
if str, ok := value.(string); ok {
if result, err := strconv.ParseInt(str, 10, 64); err == nil {
if result != 0 {
return result
}
}
}
}
return defaultValue
}