To create a single directory in Go, use the os.Mkdir()
function. If you want to create a hierarchy of folders (nested directories), use os.MkdirAll()
. Both functions require a path and permission bits of the folder as arguments.
In the examples below, we use the
os.ModePerm
constant as permission bits which is equivalent to0777
. For directories in Unix-like systems, it means that a user has rights to list, modify and search files in the directory.
Create a single directory
package main
import (
"log"
"os"
)
func main() {
if err := os.Mkdir("a", os.ModePerm); err != nil {
log.Fatal(err)
}
}
The os.Mkdir()
creates a new directory with the specified name, but cannot create subdirectories. For example, if you use os.Mkdir()
with "a/b/c/d"
as a name
argument:
os.Mkdir("a/b/c/d", os.ModePerm)
you get the error:
mkdir a/b/c/d: no such file or directory
Create a hierarchy of directories (nested directories)
package main
import (
"log"
"os"
)
func main() {
if err := os.MkdirAll("a/b/c/d", os.ModePerm); err != nil {
log.Fatal(err)
}
}
The os.MkdirAll()
creates a given directory, along with any necessary parent folder. Use this function if you need to create a nested hierarchy of directories in your program.