How to print the current path in Golang

Overview

In this shot, we will learn how to get the current path in the working directory.

We will use the Getwd() method provided by the os package in Golang to get the current path.

Return value

The Getwd() method returns two values:

  1. Directory path: The current working directory path.
  2. Error: Any error that occurs.

Code

package main
import (
"os"
"fmt"
)
func main() {
//Get working directory path
curdir, err := os.Getwd()
//check if any error occurs
if err != nil {
//display error if
fmt.Println(err)
}
//display the path
fmt.Println(curdir)
}

Explanation

In the code above:

  • Line 4: We import the os package, which provides functions like Getwd().
  • Line 5: We import the format package fmt, which is useful for formatting input and output.
  • Line 11: We call the Getwd() method and assign the two return variables to curdir and err. curdir represents the current directory and err represents error.
  • Line 14: We check if the error err is present.
    • Line 15: We print the error err if an error occurs.
  • Line 20: We print the current working directory path curdir.

We can also use _ if we don’t want to use the error value returned by Getwd(), as shown in the code snippet below:

Note: We should only use _ when we are sure there will not be any errors.

package main
import (
"os"
"fmt"
)
func main() {
//Get working directory path
curdir, _ := os.Getwd()
//display the path
fmt.Println(curdir)
}

Free Resources