CutPrefix Splits With A Found Flag

CutPrefix and CutSuffix split once and report whether the prefix matched, distinguishing an empty value from a completely different token.

GoCli Tooling

Code

gosnippet
30 lines
package main

import (
	"fmt"
	"strings"
)

// 标志走 --env: 形态,源文件走 .go 后缀:Cut* 一次拆出剩余部分与命中标志
func classifyToken(token string) string {
	if value, found := strings.CutPrefix(token, "--env:"); found {
		return "environment variable " + value
	}
	if base, found := strings.CutSuffix(token, ".go"); found {
		return "go source " + base
	}
	return "plain token " + token
}

func main() {
	for _, token := range []string{"--env:prod", "server.go", "main.py", "--env:"} {
		fmt.Println(classifyToken(token))
	}

	// found 标志区分"前缀命中但值为空"与"根本没命中"
	value, found := strings.CutPrefix("--env:", "--env:")
	fmt.Printf("cut: %q found=%v\n", value, found)

	plain, found := strings.CutPrefix("server.go", "--env:")
	fmt.Printf("cut: %q found=%v\n", plain, found)
}

Inside the snippet

the functions classifyToken and main cover the runnable surface of CutPrefix Splits With A Found Flag.

One loop does the cycling here: for _, token := range []string{"--env:prod", "server.go", "main.py", "--env:"}.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

Entry signature: func classifyToken(token string) string

Running the file prints labeled results such as cut: — every step leaves its own tagged line.

The entry point wires classifyToken together — run it once and the whole demo flows.

Core lines quoted

for _, token := range []string{"--env:prod", "server.go", "main.py", "--env:"} {
	fmt.Println(classifyToken(token))
}
func classifyToken(token string) string {
	if value, found := strings.CutPrefix(token, "--env:"); found {
		return "environment variable " + value
	}
	if base, found := strings.CutSuffix(token, ".go"); found {
		return "go source " + base
	}
	return "plain token " + token
}

Interactive Tools for This Topic

FAQ

What does CutPrefix Splits With A Found Flag print when run?
Invoke the file as-is — the `cut:` prefixes identify which step printed each line.