In Go, you cannot directly change the working directory for a specific Goroutine. Instead, the working directory is a process-wide attribute. However, you can achieve the desired behavior by using goroutines along with the os.Chdir()
function from the os
package. Here's an example:
package main
import (
"fmt"
"os"
"path/filepath"
"sync"
)
func changeDir(dir string, wg *sync.WaitGroup) {
defer wg.Done()
// Change the working directory for this Goroutine
err := os.Chdir(dir)
if err != nil {
fmt.Println("Failed to change directory:", err)
return
}
// Verify the changed directory
wd, _ := os.Getwd()
fmt.Println("Current working directory:", wd)
}
func main() {
// Get the current working directory
wd, _ := os.Getwd()
fmt.Println("Initial working directory:", wd)
// Create a wait group for synchronization
var wg sync.WaitGroup
// Define the directories to change to
directories := []string{
"/path/to/directory1",
"/path/to/directory2",
"/path/to/directory3",
}
// Launch a goroutine for each directory
for _, dir := range directories {
wg.Add(1)
go changeDir(dir, &wg)
}
// Wait for all goroutines to finish
wg.Wait()
// Verify the original working directory is restored
wd, _ = os.Getwd()
fmt.Println("Restored working directory:", wd)
}
In this example, the changeDir()
function is responsible for changing the working directory for a specific Goroutine. It uses os.Chdir()
to change the directory, and then os.Getwd()
to verify the new working directory.
The main function demonstrates how to launch multiple goroutines, each calling changeDir()
with a different directory. By using a wait group, it ensures that all goroutines have finished executing before proceeding.
Note that changing the working directory affects the entire process, so it returns to the original working directory once the goroutines have finished.