Open In App

filepath.Base() Function in Golang With Examples

Last Updated : 10 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Base() function in Go language used to return the last element of the specified path. Here the trailing path separators are removed before extracting the last element. If the path is empty, Base returns “.”. If the path consists entirely of separators, Base returns a single separator. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions.

Syntax:

func Base(path string) string

Here, ‘path’ is the specified path.

Return Value: It return the last element of the specified path. If the path is empty, this function returns “.”. If the path consists entirely of separators, this function returns a single separator.

Example 1:




// Golang program to illustrate the usage of
// filepath.Base() function
  
// Including the main package
package main
  
// Importing fmt and path/filepath
import (
    "fmt"
    "path/filepath"
)
  
// Calling main
func main() {
  
    // Calling the Base() function to
    // get the last element of path
    fmt.Println(filepath.Base("/home/gfg"))
    fmt.Println(filepath.Base(".gfg"))
    fmt.Println(filepath.Base("/gfg"))
    fmt.Println(filepath.Base(":gfg/GFG"))
}


Output:

gfg
.gfg
gfg
GFG

Example 2:




// Golang program to illustrate the usage of
// filepath.Base() function
  
// Including the main package
package main
  
// Importing fmt and path/filepath
import (
    "fmt"
    "path/filepath"
)
  
// Calling main
func main() {
  
    // Calling the Base() function which
    // returns "." if the path is empty
    // and returns a single separator if
    // the path consists entirely of separators
    fmt.Println(filepath.Base(""))
    fmt.Println(filepath.Base("."))
    fmt.Println(filepath.Base("/"))
    fmt.Println(filepath.Base("/."))
    fmt.Println(filepath.Base("//"))
    fmt.Println(filepath.Base(":/"))
      
}


Output:

.
.
/
.
/
:


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads