Go core
Browse topics

strings.Cut and related functions

Version
1.27
Since
1.18
Review
Draft

Summary#

strings.Cut splits around the first separator and reports whether it was found. CutPrefix and CutSuffix remove one fixed end. CutLast splits around the last separator.

Syntax#

go
before, after, found := strings.Cut(s, sep)
rest, found := strings.CutPrefix(s, prefix)
stem, found := strings.CutSuffix(s, suffix)
before, after, found = strings.CutLast(s, sep)

Example#

go
package main

import (
	"fmt"
	"strings"
)

func main() {
	key, value, found := strings.Cut("filter=size=large", "=")
	fmt.Printf("%q %q %t\n", key, value, found)

	token, found := strings.CutPrefix("Bearer abc123", "Bearer ")
	fmt.Printf("%q %t\n", token, found)

	stem, found := strings.CutSuffix("report.txt", ".csv")
	fmt.Printf("%q %t\n", stem, found)

	dir, name, found := strings.CutLast("logs/2026/app.log", "/")
	fmt.Printf("%q %q %t\n", dir, name, found)

	before, after, found := strings.CutLast("app.log", "/")
	fmt.Printf("%q %q %t\n", before, after, found)
}

Expected output#

Text
"filter" "size=large" true
"abc123" true
"report.txt" false
"logs/2026" "app.log" true
"app.log" "" false

Common mistakes#

Check found before using the parts. When the separator is missing, both Cut and CutLast return the whole input as before and an empty after. For a file name without a directory, that puts the name in before.

Version applicability#

Cut was added in Go 1.18 and CutPrefix and CutSuffix in Go 1.20. The complete example requires Go 1.27 for CutLast. On older versions, split with Index or LastIndex and slicing. For prefixes, pair HasPrefix with TrimPrefix. For suffixes, use HasSuffix with TrimSuffix.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0