Library contents

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

  1. Start with "a=b"
  2. Do this Split at the first equals sign
  3. Result Left a, right b
The equals sign marks the boundary between the two fields.

Syntax

Go 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.

From the programfor _, field := range []string{"token=a=b", "mode=", "broken"} {
First output linetoken [a=b]
main.go
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)
	}
}
Output
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

Advertisements

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.

Givensource=HDMI2
Worked resultHDMI2

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.

Givenrule=x=y
Worked resultx=y