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.
Code
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
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.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.