diff --git a/string.go b/string.go index 2f0d41e..7779e7b 100644 --- a/string.go +++ b/string.go @@ -138,6 +138,15 @@ func TryToString(v any) (string, error) { return TryStr(v) } +// IsStr returns true if value is string +func IsStr(v any) bool { + if v == nil { + return false + } + _, ok := v.(string) + return ok +} + // IsStrContainsOf returns true if input string contains only chars from subset func IsStrContainsOf(s, subset string) bool { if len(s) == 0 { diff --git a/string_test.go b/string_test.go index e01203d..9236308 100644 --- a/string_test.go +++ b/string_test.go @@ -43,6 +43,25 @@ func TestToString(t *testing.T) { } } +func TestIsStr(t *testing.T) { + tests := []struct { + value any + target bool + }{ + {value: 1, target: false}, + {value: nil, target: false}, + {value: int8(1), target: false}, + {value: int16(1), target: false}, + {value: []byte("notstr"), target: false}, + {value: []int8{1, 2, 3, 4, 5}, target: false}, + {value: []any{'1', '2', '3'}, target: false}, + {value: "str", target: true}, + } + for _, test := range tests { + assert.Equal(t, IsStr(test.value), test.target) + } +} + func BenchmarkToStringByReflect(b *testing.B) { b.ReportAllocs() b.RunParallel(func(pb *testing.PB) {