Strings concatenation is a great topic to learn through TDD, but this topic is not covered in this chapter.
Strings in Go are immutable, so memory reallocates on every change of a string. We can demonstrate this with an example by benchmarking and show a solution: strings.Builder from the strings package.
To do this we can:
Add benchmarking before the refactoring stage and run it.
Provide a short explanation about strings in Go, explaining the purpose of using strings.Builder.
Add strings.Builder in the refactor stage. The final function will look like:
const repeatCount = 5
func Repeat(character string) string {
var sb strings.Builder // do not forget to import "strings"
for i := 0; i < repeatCount; i++ {
sb.WriteString(character)
}
return sb.String()
}
Launch becnhmarking after refactoring
I can make a pull request with this changes, if you want.
I think that work with strings can be discussed after the chapter on arrays and slices. This section can cover not only strings.Builder, but also runes, bytes, and work with UTF-8.
Strings concatenation is a great topic to learn through TDD, but this topic is not covered in this chapter.
Strings in Go are immutable, so memory reallocates on every change of a string. We can demonstrate this with an example by benchmarking and show a solution:
strings.Builder
from thestrings
package.To do this we can:
strings.Builder
.Add
strings.Builder
in the refactor stage. The final function will look like:I can make a pull request with this changes, if you want.