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:
Directory path: The current working directory path.Error: Any error that occurs.
Code
package mainimport ("os""fmt")func main() {//Get working directory pathcurdir, err := os.Getwd()//check if any error occursif err != nil {//display error iffmt.Println(err)}//display the pathfmt.Println(curdir)}
Explanation
In the code above:
- Line 4: We import the
ospackage, which provides functions likeGetwd(). - 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 tocurdiranderr.curdirrepresents the current directory anderrrepresents error. - Line 14: We check if the error
erris present.- Line 15: We print the error
errif an error occurs.
- Line 15: We print the error
- 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 mainimport ("os""fmt")func main() {//Get working directory pathcurdir, _ := os.Getwd()//display the pathfmt.Println(curdir)}