find the parent directory of a directory in go

To find the parent directory of a directory in Go, we can make use of the path/filepath package. Specifically, we can use the Dir function to get the parent directory of any given file or directory.

main.go
package main

import (
    "fmt"
    "path/filepath"
)

func main() {
    // the directory we want to find the parent directory of
    dir := "/path/to/child/directory"

    // get the parent directory
    parentDir := filepath.Dir(dir)

    // print the result
    fmt.Println(parentDir)
}
291 chars
18 lines

In the example above, we first define the directory we want to find the parent directory of using the dir variable. We then use the filepath.Dir() function to get the parent directory, and store the result in the parentDir variable. Finally, we print the result to the console.

gistlibby LogSnag