Standard library / os

os.Rename()

Renames or moves a file within supported filesystem boundaries; replacement and atomicity rules vary by OS. Example uses a disposable temporary workspace. Expected stdout: 'abc\n'.

Formal Syntax & Structure

go syntaxgo
func Rename(oldpath, newpath string) error

Parameters & Attributes

NameTypeDescription
oldpathstringInput to os.Rename(); see the operation contract.
newpathstringInput to os.Rename(); see the operation contract.

Return Value

error

Renames or moves a file within supported filesystem boundaries; replacement and atomicity rules vary by OS.

Working Example

Example Snippetgo
package main
import (  "fmt"  "os")
func check(e error) {  if e != nil {    panic(e)  }}func seed() { check(os.WriteFile("a.txt", []byte("abc"), 0600)) }func workspace() func() {  root, e := os.MkdirTemp("", "bytemind-go-")  check(e)  old, e := os.Getwd()  check(e)  check(os.Chdir(root))  return func() { check(os.Chdir(old)); check(os.RemoveAll(root)) }}func main() {  defer workspace()()  seed()  check(os.Rename("a.txt", "b.txt"))  b, e := os.ReadFile("b.txt")  check(e)  fmt.Println(string(b))}
Go Reference