move a file in go

To move a file or rename it in Go, you can use the Rename function from the os package. Here's an example:

main.go
package main

import (
    "fmt"
    "os"
)

func main() {
    oldPath := "old/file.txt"
    newPath := "new/file.txt"

    err := os.Rename(oldPath, newPath)
    if err != nil {
        fmt.Println("Error moving file:", err)
        return
    }

    fmt.Println("File moved successfully")
}
293 chars
20 lines

In this code snippet, we specify the old path and the new path of the file we want to move or rename. We then call the Rename function from the os package, passing in the old path and the new path as arguments.

If there is an error while moving or renaming the file, the Rename function returns an error value. We can check for this error and handle it accordingly.

Note that if the new path already exists, the Rename function will replace it with the file being moved. Also, the Rename function works only within the same file system. If you want to move a file to a different file system or partition, you need to copy the file and then delete the original.

related categories

gistlibby LogSnag