move a directory in go

You can move a directory in Go by using the os.Rename() function which can be used to rename or move a file or directory in the file system.

The os.Rename() function takes two arguments, the current path of the file/directory and the new path of the file/directory. Here is an example usage to move a directory:

main.go
package main

import (
    "fmt"
    "os"
)

func main() {
    // current path of directory to be moved
    currentPath := "/path/to/current/directory"
  
    // new path for directory
    newPath := "/path/to/new/directory"
    
    // Rename function will move the directory to new path and also rename it if needed
    err := os.Rename(currentPath, newPath)
    if err != nil {
        fmt.Println(err)
    }
}
414 chars
21 lines

Note that when moving a directory, the new path must not exist already. If it does, an error will be returned.

related categories

gistlibby LogSnag