Cut Strings At The First Separator

Parse host:port and key=value pairs with strings.Cut, which splits at the first separator and reports before, after, and whether a separator was found.

GoCli Tooling

Code

gosnippet
33 lines
package main

import (
	"fmt"
	"strings"
)

func main() {
	// strings.Cut splits at the first separator only: a before/after/found triple
	addr := "db.internal:5432"
	host, port, ok := strings.Cut(addr, ":")
	fmt.Printf("host=%q port=%q found=%v\n", host, port, ok)

	// No separator: the whole string lands in before, after is empty, found is false
	noPort, _, found := strings.Cut("localhost", ":")
	fmt.Printf("noPort=%q found=%v\n", noPort, found)

	// With several separators only the first splits: the rest stays intact in after
	first, rest, _ := strings.Cut("k1=v1=k2", "=")
	fmt.Printf("first=%q rest=%q\n", first, rest)

	// Cutting into after repeatedly walks every k=v field
	line := "user=ada,role=admin,team=core"
	for {
		field, next, more := strings.Cut(line, ",")
		k, v, _ := strings.Cut(field, "=")
		fmt.Printf("%s=%s\n", k, v)
		if !more {
			break
		}
		line = next
	}
}

How the snippet works

Under the hood: the function main.

The one repetition in this snippet is the loop for.

Points of care

  • Built-in APIs only, so there is no supply chain to vet.

Using it

The demo output is labeled (host=, noPort=, first=), so each line traces straight back to the statement that printed it.

Key statements

noPort, _, found := strings.Cut("localhost", ":")

Interactive Tools for This Topic

FAQ

What does Cut Strings At The First Separator print when run?
No setup needed: run the file and look for labeled lines like `host=`, `noPort=`, `first=` in the output.