Standard library / os

os.Chdir()

Changes process-wide working directory. Avoid it in concurrent application logic; prefer explicit paths. Example uses a disposable temporary workspace. Expected stdout: 'sub\n'.

Formal Syntax & Structure

go syntaxgo
func Chdir(dir string) error

Parameters & Attributes

NameTypeDescription
dirstringDirectory pathname.

Return Value

error

Changes process-wide working directory.

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))  check(os.Chdir("sub"))  p, e := os.Getwd()  check(e)  fmt.Println(filepath.Base(p))}
Go Reference