función filepath.Dir() en Golang con ejemplos

En el lenguaje Go, el paquete de ruta se usa para rutas separadas por barras inclinadas, como las rutas en las URL. La función filepath.Dir() en el lenguaje Go solía devolver todos los elementos de la ruta especificada excepto el último elemento. Después de colocar el elemento final, Dir llama a Limpiar en la ruta y se eliminan las barras diagonales. Si la ruta está vacía, Dir devuelve “.”. Si la ruta consta completamente de separadores, Dir devuelve un único separador. La ruta devuelta no termina en un separador a menos que sea el directorio raíz. Además, esta función se define en el paquete de ruta. Aquí, debe importar el paquete «ruta/ruta de archivo» para usar estas funciones.

Sintaxis:

func Dir(path string) string

Aquí, ‘ruta’ es la ruta especificada.

Valor devuelto: Devuelve todos los elementos de la ruta especificada excepto el último elemento.

Ejemplo 1:

// Golang program to illustrate the usage of
// filepath.Dir() function
  
// Including the main package
package main
  
// Importing fmt and path/filepath
import (
    "fmt"
    "path/filepath"
)
  
// Calling main
func main() {
  
    // Calling the Dir() function
    fmt.Println(filepath.Dir("/Geeks/GFG/gfg.org"))
    fmt.Println(filepath.Dir("/Geeks/GFG/gfg"))
    fmt.Println(filepath.Dir("/Geeks/GFG/gfg/"))
    fmt.Println(filepath.Dir("/GFG/gfg///"))
    fmt.Println(filepath.Dir("/gfg.org"))
    fmt.Println(filepath.Dir("gfg.org"))
}

Producción:

/Geeks/GFG
/Geeks/GFG
/Geeks/GFG/gfg
/GFG/gfg
/
.

Ejemplo 2:

// Golang program to illustrate the usage of
// filepath.Dir() function
  
// Including the main package
package main
  
// Importing fmt and path/filepath
import (
    "fmt"
    "path/filepath"
)
  
// Calling main
func main() {
  
    // Calling the Dir() function
    fmt.Println(filepath.Dir(""))
    fmt.Println(filepath.Dir("."))
    fmt.Println(filepath.Dir("/"))
    fmt.Println(filepath.Dir("//"))
    fmt.Println(filepath.Dir("../gfg.org"))
  
}

Producción:

.
.
/
/
..

Publicación traducida automáticamente

Artículo escrito por Kanchan_Ray y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *