Go: Distinguish missing separators from empty values with strings.Cut
A configuration entry such as mode= has a delimiter and an empty value. mode has no delimiter. Use the boolean returned by strings.Cut to keep those cases separate.
Set up
Tested on Linux with Go 1.26.10. Use Bash with Go on your PATH. Keep the same terminal through cleanup, and stop if setup fails.
start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1Run the example
Save as strings_cut_empty_values.go:
package main
import (
"fmt"
"strings"
)
func main() {
for _, input := range []string{"mode=fast", "mode=", "mode", "token=a=b", "=value"} {
key, value, found := strings.Cut(input, "=")
fmt.Printf("%q: key=%q value=%q found=%t\n", input, key, value, found)
}
}go run strings_cut_empty_values.goObserved output:
"mode=fast": key="mode" value="fast" found=true
"mode=": key="mode" value="" found=true
"mode": key="mode" value="" found=false
"token=a=b": key="token" value="a=b" found=true
"=value": key="" value="value" found=trueRead the result
The split stops at the first equals sign, so the token value keeps its second equals sign. Checking only whether the value is empty would confuse the two mode cases. An empty key is another independent validation decision.
Apply it carefully
This is a delimiter split, not a quoted configuration-file parser. Decide whether empty keys, empty values, or whitespace are legal before accepting the result. The example intentionally preserves all input characters and performs no trimming.
See the Go standard-library reference.
Clean up
Remove the source and the empty scratch directory. Go may retain build-cache files outside this directory. If the directory is not empty, inspect its contents before removing anything else.
rm -- strings_cut_empty_values.go
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dirAcknowledgements
This post was created with assistance from AI.