×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

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

Given a path, we have to check if a path is an absolute path in Golang.
Submitted by IncludeHelp, on October 28, 2021 [Last updated : March 05, 2023]

Checking if a path is an absolute path in Golang

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.

Syntax

func IsAbs(path string) bool

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

Golang code 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.

Golang path/filepath Package Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.