← 中文资源

简体中文版本

用 strings.Cut 按首个分隔符切分

strings.Cut 只在第一个分隔符处切开,返回 before、after 与 found 标记;解析 host:port、key=value 这类片段不再需要手写索引运算,找不到分隔符时 found 为 false。

阅读英文原文

实现说明

用 strings.Cut 按首个分隔符切分可以归结为函数 main。 循环只出现在 for,它的每次迭代处理一个元素。

使用要点

  • 直接运行文件,输出会带上标签,比如 host=、noPort=、first=——输出的每一行都能指回产生它的那次调用。

常见问题

运行「用 strings.Cut 按首个分隔符切分」会打印什么?

运行文件本身,host=、noPort=、first= 这些前缀各对应一段演示逻辑。

核心语句

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

代码示例

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
	}
}