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.
Code
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
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.