Q:

How to check if a path is an absolute path in Golang?

belongs to collection: Golang path/filepath Package Programs

0

In the Go programming language, to check whether the given path is an absolute path or not – we use the IsAbs() function of the path/filepath package. The IsAbs() function true if the given path is an absolute path; false, otherwise.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Syntax:

func IsAbs(path string) bool

Consider the below Golang program demonstrating how to check if a path is an absolute path?

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	// Defining paths
	path1 := "/programs/course1/hello1.go"
	path2 := "../programs/course1/hello1.go"
	path3 := "C:/programs/course1/hello1.go"

	// Calling IsAbs() to check the path
	// whether absolute or not
	if filepath.IsAbs(path1) {
		fmt.Println(path1, " is an absolute path.")
	} else {
		fmt.Println(path1, " is not an absolute path.")
	}

	if filepath.IsAbs(path2) {
		fmt.Println(path2, " is an absolute path.")
	} else {
		fmt.Println(path2, " is not an absolute path.")
	}

	if filepath.IsAbs(path3) {
		fmt.Println(path3, " is an absolute path.")
	} else {
		fmt.Println(path3, " is not an absolute path.")
	}
}

Output

/programs/course1/hello1.go  is an absolute path.
../programs/course1/hello1.go  is not an absolute path.
C:/programs/course1/hello1.go  is not an absolute path.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

How to join multiple paths into a single path in G... >>
<< How to get the volume name from a path in Golang?...