Skip to content

Commit

Permalink
Added new OrElseNilSafe to handle nil pointers for optional strings. (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
ferreiraad authored Nov 2, 2024
1 parent e959274 commit c5e194a
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions strutil/strutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 != "" {
Expand Down
6 changes: 6 additions & 0 deletions strutil/strutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down

0 comments on commit c5e194a

Please sign in to comment.