Go strings.Cut
strings.Cut returns the text before and after the first separator and a boolean indicating whether it found that separator.
A simple example
strings.Cut
- Start with "a=b"
- Do this Split at the first equals sign
- Result Left a, right b
Syntax
before, after, found := strings.Cut(text, separator)
Run this example in Go
Save the program as main.go. Use Go 1.21 or later.
go run main.go
Split a configuration field at its first separator
A configuration line separates a key from its value with punctuation. Split only at the first intended boundary because the value itself may contain the same separator later on.
package main
import (
"fmt"
"strings"
)
func main() {
for _, field := range []string{"token=a=b", "mode=", "broken"} {
key, value, ok := strings.Cut(field, "=")
if !ok {
fmt.Println("missing separator")
continue
}
fmt.Printf("%s [%s]\n", key, value)
}
}
token [a=b] mode [] missing separator
Checking found distinguishes an empty value from a missing equals sign. Any further separators stay in the value.
Go documentation for strings.Cut
Read a projector setting
A teacher saves a projector source in a configuration line. The first equals sign separates the key from its value. Keep the entire suffix, including any later equals sign.
Preserve a calibration formula
A lab note stores a comparison as the value of a setting. The first equals sign separates the key from its value. Keep the entire suffix, including any later equals sign.