find the root directory of a directory in go

To find the root directory of a given directory in Go, we can use the filepath.VolumeName() function. Here's an example code snippet:

main.go
package main

import (
    "fmt"
    "path/filepath"
)

func main() {
    directory := "/home/user/files"

    root := filepath.VolumeName(directory)

    fmt.Println("Root directory:", root)
}
194 chars
15 lines

In this example, we have a directory variable set to the path of a directory. The filepath.VolumeName() function returns the volume name (i.e., the root directory) of the path specified in directory. We then print out the root directory using fmt.Println().

Note that the filepath.VolumeName() function is only available on Windows, and will return an empty string on Unix-based systems. In that case, we can assume that the root directory is simply "/" (the root of the file system).

gistlibby LogSnag