Understand the contract
A Go string is an immutable sequence of bytes. len reports bytes, and indexing returns a byte. Many strings contain UTF-8 text, but a string can also hold arbitrary bytes. Use the strings package for common text operations and the Unicode-aware tools from the next lesson when code points matter.
TrimSpace returns a string with leading and trailing Unicode whitespace removed. Split separates at each occurrence of a separator and Join combines a slice with a chosen separator. None of these operations mutates the input string. Store the returned result before using the transformed text.
Work through the example
The example turns a padded comma-separated string into go | api | tests. It is a small controlled format, not a CSV parser: quoted commas and embedded newlines require encoding/csv. Choosing a standard parser becomes necessary as soon as the input grammar grows beyond a plain separator.
package main
import (
"fmt"
"strings"
)
func main() {
input := " go,api,tests "
parts := strings.Split(strings.TrimSpace(input), ",")
fmt.Println(strings.Join(parts, " | "))
}Watch this boundary
Byte slicing can split a UTF-8 encoding in the middle of a character. It also cannot safely truncate user-visible grapheme clusters. Avoid applying a byte limit as a display-character limit. For constructing many pieces, consider strings.Builder after correctness is clear and measurements justify the choice.
Practice with a changed input
Try an empty string and a trailing comma, then inspect the resulting slices. Decide whether empty fields should be retained, removed or rejected by your input rules.
Lesson 17 of 50
View the full Go basics seriesReferences & further reading
Need help with your Go backend?
I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.
Explore Go consulting services