gopath

How to go 1 level back for a directory path stored in a variable


I'm trying to go back 1 level back in a stored variable in Go Lang, how could I do this?

Origin:
"/root/path"

Expected:
"/root/"

There's a function that could do that automatically? or I have to do it manually?

Thanks.


Solution

  • The parent directory can always be referred to by .., so you can append that to your path.

    For example:

    p := "/root/path/"
    p = filepath.Clean(filepath.Join(p, ".."))
    fmt.Println(p)
    // "/root"
    

    If path is not a directory itself (or you are certain that it will not end in a path separator), then you can use the Dir function to get the containing directory. Dir returns all but the last element of path, typically the path's directory:

    p := "/root/path"
    p = filepath.Dir(p)
    fmt.Println(p)
    // "/root"