TrimLeft Cutset Versus Prefix

Strip leading characters correctly: strings.TrimLeft removes any leading cutset runes, TrimPrefix removes one exact prefix, and confusing them corrupts data.

GoData Integrity

Code

gosnippet
28 lines
package main

import (
	"fmt"
	"strings"
)

func main() {
	padded := "    42"

	// TrimLeft + cutset:" " 会重复剥掉所有前导空格
	fmt.Println("trimleft:", strings.TrimLeft(padded, " "))

	// TrimPrefix 只删一个精确前缀:多一个空格就原样保留
	fmt.Println("trimprefix 1:", strings.TrimPrefix(padded, " "))
	fmt.Println("trimprefix 4:", strings.TrimPrefix(padded, "    "))

	// 多字符 cutset:剥掉任意组合的前导字符
	fmt.Println("cutset:", strings.TrimLeft("00xFF", "0x"))

	// 经典误用:cutset 是字符集合不是前缀——"//path" 上
	// TrimLeft 剥光所有前导 '/',TrimPrefix 只删一层
	fmt.Println("cutset strips all:", strings.TrimLeft("//path", "/"))
	fmt.Println("prefix strips one:", strings.TrimPrefix("//path", "/"))

	// TrimRight 对称:剥掉尾部任意组合
	fmt.Println("trimright:", strings.TrimRight("report.txt.tmp", ".tmp"))
}

What the code does

TrimLeft Cutset Versus Prefix keeps everything in the function main.

What to watch for

  • The runtime is the only requirement — no packages, no install.

Applying it

The demo output is labeled (trimleft:, trimprefix 1:, trimprefix 4:), so the output doubles as a step-by-step trace of what the file did.

Statements that matter

padded := "    42"

Interactive Tools for This Topic

FAQ

What does TrimLeft Cutset Versus Prefix print when run?
Execute the whole file; each printed line is prefixed with a label like `trimleft:`, `trimprefix 1:`, `trimprefix 4:`.