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 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) }
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 main import ( "os" "fmt" ) func main() { //Get working directory path curdir, _ := os.Getwd() //display the path fmt.Println(curdir) }
RELATED TAGS
CONTRIBUTOR
View all Courses