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.
The Getwd()
method returns two values:
Directory path
: The current working directory path.Error
: Any error that occurs.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)}
In the code above:
os
package, which provides functions like Getwd()
.fmt
, which is useful for formatting input and output.Getwd()
method and assign the two return variables to curdir
and err
. curdir
represents the current directory and err
represents error.err
is present.
err
if an error occurs.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)}