Golang filepath.Base() 函数的使用和实例

Golang filepath.Base() 函数的使用和实例

Go 语言中,path 包用于以正斜杠分隔的路径,例如 URL 中的路径。Go 语言中的 filepath.Base() 函数用于返回指定路径的最后一个元素。在提取最后一个元素之前,移除尾部的路径分隔符。如果路径为空,则 Base 返回“.”。如果路径完全由分隔符组成,则 Base 返回单个分隔符。此函数受 path 包的定义。在这里,您需要导入“path/filepath”包才能使用这些函数。

Syntax:

func Base(path string) string

在这里,“path”是指定的路径。

Return Value: 它返回指定路径的最后一个元素。如果路径为空,则此函数返回“.”。如果路径完全由分隔符组成,则此函数返回单个分隔符。

示例 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"))
} 

输出:

gfg
.gfg
gfg
GFG

示例 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(":/"))
      
} 

输出:

.
.
/
.
/
:

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程