How to split the path into a list of individual paths in Golang?

Given a path, we have to split the path into a list of individual paths.
Submitted by IncludeHelp, on October 27, 2021 [Last updated : March 05, 2023]

Splitting the path into a list of individual paths in Golang

In the Go programming language, to split the path into a list of individual paths – we use the SplitList() function of path/filepath package. The SplitList() function splits a list of paths joined by the OS-specific ListSeparator (usually found in PATH or GOPATH environment variables). Unlike strings.Split(), SplitList() returns an empty slice when passed an empty string.

Syntax:

func SplitList(path string) []string

Consider the below Golang program demonstrating how to split the path into a list of individual paths (array of strings)?

Golang code to split the path into a list of individual paths

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	// Path value
	path := "/usr/local/go/bin:/usr/local/bin:/usr/bin:/usr/sbin"
	result := filepath.SplitList(path)

	// Printing the paths (array of string)
	fmt.Println("Paths (array of string)...")
	fmt.Printf("%q\n\n", result)

	// Printing the list of individual paths
	fmt.Println("List of individual paths...")
	for i := range result {
		fmt.Println(result[i])
	}
}

Output

Paths (array of string)...
["/usr/local/go/bin" "/usr/local/bin" "/usr/bin" "/usr/sbin"]

List of individual paths...
/usr/local/go/bin
/usr/local/bin
/usr/bin
/usr/sbin

Golang path/filepath Package Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.