multistring defines a new type, Wrap, that has the underlying type []string, with methods defined on it that correspond to1 the free functions in the standard library's strings package. Each method performs the equivalent of applying the corresponding function over the slice, like the map higher-order function would.
w := multistring.Wrap{" apple ", "banana ", " celery"}
s := w.TrimSpace().ToUpper().Repeat(3).JoinBy(",")
println(s)
// APPLEAPPLEAPPLE,BANANABANANABANANA,CELERYCELERYCELERYThe methods' signatures are derived from those of the corresponding functions, subject to two transformations:
- The elements in the
Wrapwill be implicitly passed as the first string argument to thestringsfunction - Every return type
Twill be transformed to the slice type[]T, unlessTisstring, in which case it will be transformed toWrap, to allow chaining.
There are two additional methods on Wrap that are not derived from strings, JoinBy and MapString:
JoinBycan be used for cases where, as a final step, you want to join a group of strings (contained in aWrap) with the same separator, rather than join a group of strings (passed to theJoinmethod) with a group of separators contained in aWrap.MapStringis the analogue ofstrings.Map, but taking a function that takes astring(func(string) string), instead of arune.
For a side project, I needed to apply functions from strings over slices of strings. After writing a few for loops, I decided to abstract it out into what is now Wrap, and then I thought - what if I could generate these method definitions?
A couple of days later...