Standard library / os
os.File.Chdir()
Changes process-wide working directory to the open directory handle; avoid in concurrent code. Example uses a disposable temporary workspace. Expected stdout: 'sub\n'.
Formal Syntax & Structure
go syntaxgo
func (f *File) Chdir() errorReturn Value
error
Changes process-wide working directory to the open directory handle; avoid in concurrent code.
Working Example
Example Snippetgo
package main
import ( "fmt" "os" "path/filepath")
func check(e error) { if e != nil { panic(e) }}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()() check(os.Mkdir("sub", 0700)) f, e := os.Open("sub") check(e) defer f.Close() check(f.Chdir()) p, e := os.Getwd() check(e) fmt.Println(filepath.Base(p))}