filepath.SplitList Path Lists

Split PATH-style environment values with filepath.SplitList, which uses the OS list separator, and rejoin them without guessing the delimiter.

GoConfig Management

Code

snippet
package main

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"
	"strings"
)

func main() {
	// PATH 风格列表的分隔符随平台变化:Unix 是 ':',Windows 是 ';'
	list := "/usr/local/bin:/usr/bin:/opt/tools"
	if runtime.GOOS == "windows" {
		list = `C:\Go\bin;C:\tools;C:\Windows\System32`
	}

	dirs := filepath.SplitList(list)
	fmt.Println("separator:", string(os.PathListSeparator))
	fmt.Println("entries:", len(dirs))
	for i, dir := range dirs {
		fmt.Printf("  %d: %q\n", i, dir)
	}

	// 反向拼回去必须用同一个分隔符,不能写死 ":" 或 ";"
	fmt.Println("rejoined:", strings.Join(dirs, string(os.PathListSeparator)))

	// 条目的含义由调用方定义:这里是 PATH,GOPATH 等多值变量同样适用
	for _, dir := range filepath.SplitList(os.Getenv("PATH")) {
		if strings.HasSuffix(dir, "go") {
			fmt.Println("first matching dir:", dir)
			break
		}
	}
}

Tracing one pass of the file

Everything happens inside the function main.

A single loop drives the file — for i, dir := range dirs.

Configuration comes from the environment — it reads PATH, so the same code switches behavior between environments without edits.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

Execution starts at func main()

The printed lines announce themselves (separator:, entries:, rejoined:), one per stage.

Key statements

for _, dir := range filepath.SplitList(os.Getenv("PATH")) {
	if strings.HasSuffix(dir, "go") {
		fmt.Println("first matching dir:", dir)
		break
	}
}
for i, dir := range dirs {
	fmt.Printf("  %d: %q\n", i, dir)
}

Interactive Tools for This Topic

FAQ

What does filepath.SplitList Path Lists print when run?
Invoke the file as-is — the `separator:`, `entries:`, `rejoined:` prefixes identify which step printed each line.