SplitN Caps The Number Of Substrings

Split a connection string or key-value pair with strings.SplitN so the remainder stays intact as one field instead of being shredded into extra segments.

GoConfig Management

Code

gosnippet
23 lines
package main

import (
	"fmt"
	"strings"
)

func main() {
	conn := "postgres://user:secret@db:5432/app?sslmode=require"

	// n=2:只在第一个 :// 处切开,右侧完整保留
	parts := strings.SplitN(conn, "://", 2)
	fmt.Println("scheme:", parts[0])
	fmt.Println("rest:", parts[1])

	// n=3:把等号右边带等号的查询值整段保住
	kv := "token=abc=def=ghi"
	kvParts := strings.SplitN(kv, "=", 2)
	fmt.Printf("key=%q value=%q\n", kvParts[0], kvParts[1])

	// 对照:不带上限的 Split 会切出超出预期的段数
	fmt.Println("plain Split:", strings.Split(kv, "="))
}

The mechanics

SplitN Caps The Number Of Substrings keeps everything in the function main.

What to watch for

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

Putting it to use

Output lines are prefixed (scheme:, rest:, key=), so each step’s effect lands on its own line.

Lines that carry the behavior

conn := "postgres://user:secret@db:5432/app?sslmode=require"

Interactive Tools for This Topic

FAQ

What does SplitN Caps The Number Of Substrings print when run?
Invoke the file as-is — the `scheme:`, `rest:`, `key=` prefixes identify which step printed each line.