use the os package to get the current working directory and print it in go

To get the current working directory using the os package in Go, you can use the Getwd() function, which returns a string containing the path of the current working directory. Here's an example code snippet:

main.go
package main

import (
    "fmt"
    "os"
)

func main() {
    cwd, err := os.Getwd()
    if err != nil {
        fmt.Println("Error getting current working directory:", err)
        return
    }
    fmt.Println("Current working directory:", cwd)
}
249 chars
16 lines

In this example, we import the fmt and os packages, then use the Getwd() function to get the current working directory. We use the if err != nil construct to check if any error occurred while getting the directory, and print the error message if there was one. Finally, we print the current working directory to the console using fmt.Println().

gistlibby LogSnag