diff --git a/README.md b/README.md index 22cd6255e..fa85d8961 100644 --- a/README.md +++ b/README.md @@ -1417,6 +1417,7 @@ func BlankOr(val, defVal string) string func ZeroOr[T ~string](val, defVal T) T func ErrorOr(s string, err error, defVal string) string func OrElse(s, orVal string) string +func OrElseNilSafe(s *string, orVal string) string func OrHandle(s string, fn comdef.StringHandleFunc) string func Valid(ss ...string) string func Replaces(str string, pairs map[string]string) string diff --git a/README.zh-CN.md b/README.zh-CN.md index aca933bed..9cffe7199 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -1418,6 +1418,7 @@ func BlankOr(val, defVal string) string func ZeroOr[T ~string](val, defVal T) T func ErrorOr(s string, err error, defVal string) string func OrElse(s, orVal string) string +func OrElseNilSafe(s *string, orVal string) string func OrHandle(s string, fn comdef.StringHandleFunc) string func Valid(ss ...string) string func Replaces(str string, pairs map[string]string) string diff --git a/strutil/strutil.go b/strutil/strutil.go index 7a2ca434b..9e46773b9 100644 --- a/strutil/strutil.go +++ b/strutil/strutil.go @@ -51,6 +51,14 @@ func OrElse(s, orVal string) string { return orVal } +// OrElseNilSafe return default value on s is nil, otherwise return s +func OrElseNilSafe(s *string, orVal string) string { + if s == nil || *s == "" { + return orVal + } + return *s +} + // OrHandle return fn(s) on s is not empty. func OrHandle(s string, fn comdef.StringHandleFunc) string { if s != "" { diff --git a/strutil/strutil_test.go b/strutil/strutil_test.go index 11bfa41a3..e7a23f89e 100644 --- a/strutil/strutil_test.go +++ b/strutil/strutil_test.go @@ -25,6 +25,12 @@ func TestValid(t *testing.T) { is.Eq("cd", strutil.OrElse("", "cd")) is.Eq("ab", strutil.OrElse("ab", "cd")) + var str = "non-empty" + is.Equal(str, strutil.OrElseNilSafe(&str, "fallback")) + str = "" + is.Equal("fallback", strutil.OrElseNilSafe(&str, "fallback")) + is.Equal("default", strutil.OrElseNilSafe(nil, "default")) + is.Eq(" ", strutil.ZeroOr(" ", "cd")) is.Eq("cd", strutil.ZeroOr("", "cd")) is.Eq("ab", strutil.ZeroOr("ab", "cd"))