DEV Community

Cover image for How to work with paths join or change directories in Golang
Mohamed Allam
Mohamed Allam

Posted on • Originally published at go.mohamedallam.tech

How to work with paths join or change directories in Golang

Path join in Golang

Manipulating filename paths in a way that is compatible with the any target operating system-defined file paths.

Path joining

When you start changing directories, you have to work with both forward slash and backward slash, depending on the operating system, Unix or Windows, Go takes care of that using path.FilePath.Join function, to use Join, you have to provide the name of the folders, and Go will use the appropriate slash for you

// https://pkg.go.dev/path/filepath#Join
func Join(elem ...string) string {
...
}
Enter fullscreen mode Exit fullscreen mode

Join joins any number of path elements into a single path, separating them with an OS specific Separator. Empty elements are ignored. The result is Cleaned. However, if the argument list is empty or all its elements are empty, Join returns an empty string. On Windows, the result will only be a UNC path if the first non-empty element is a UNC path.

To use that, let's change directory using Go.

Change directory cd

And also we generally you would need to use the [chdir](https://pkg.go.dev/os#Chdir) you specify the name of the directory you want to go to, and this function would change the current directory for you

// https://pkg.go.dev/os#Chdir
func Chdir(dir string) error {
...
}
Enter fullscreen mode Exit fullscreen mode

Chdir changes the current working directory to the named directory. If there is an error, it will be of type *PathError.

Lets combine this two, which does allow us to work with either windows or linux who use / or \ backslash and forward slash for each system, and change directory to for now the names we pass in the ChangeDir

func ChangeDir(elem ...string) {
    path := filepath.Join("./", filepath.Join(elem...))

    err := os.Chdir(path)
    if err != nil {
        fmt.Println("Cant change the workig directory", err)
    }
}
Enter fullscreen mode Exit fullscreen mode

Joining strings

On the same note, if for whatever reason you want to join folder names, based on something different, or if is any strings joined, there is in the Go standard package, a string package that has a join method that is as below

https://pkg.go.dev/strings#Join
func Join(elems []string, sep string) string
Enter fullscreen mode Exit fullscreen mode

Join concatenates the elements of its first argument to create a single string. The separator string sep is placed between elements in the resulting string.

And as the official documentation:

s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
//Output
//foo, bar, baz
Enter fullscreen mode Exit fullscreen mode

Top comments (0)