This is my custom function to join strings from an array into one string.
We can provide normal separator and the last one. JoinStringsIntoArray(", ", " and ", words...)
func JoinStringsIntoArray(sep string, lastSep string, words ...string) string {
lastElementIndex := len(words) - 1
var joinedString string
for index, word := range words[0:lastElementIndex] {
if index == lastElementIndex-1 {
sep = lastSep
}
joinedString += word + sep
}
joinedString += words[lastElementIndex]
return joinedString
}
Test for this function
func TestStringsJoinsWithCommas(t *testing.T) {
var words []string
words = append(words, "one", "two", "three")
expectedResult := "one, two and three"
result := JoinStringsIntoArray(", ", " and ", words...)
if expectedResult != result {
t.Errorf("Strings joiner is broken, it should be '%v', we got '%v'", expectedResult, result)
}
}
What do you think about this, can this solution be improved? The function works fine but I'm not so sure it's written well.