×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

How to get the absolute path from a relative path in Golang?

Given a relative path, we have to find the absolute path in Golang.
Submitted by IncludeHelp, on October 27, 2021 [Last updated : March 05, 2023]

Getting the absolute path from a relative path in Golang

In the Go programming language, to get the absolute path from a relative path – we use the Abs() function of path/filepath package. The Abs() function returns an absolute representation of the path. If the given path is not absolute it will be joined with the current working directory to turn it into an absolute path. The absolute pathname for a given file is not guaranteed to be unique.

Syntax:

func Abs(path string) (string, error)

Consider the below Golang program demonstrating how to get the absolute path from a relative path?

Golang code to get the absolute path from a relative path

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	// Getting absolute path of hello.go
	abs, err := filepath.Abs("./hello.go")

	// Printing if there is no error
	if err == nil {
		fmt.Println("Absolute path is:", abs)
	}
}

Output

Absolute path is: /hello.go

Note: The absolute path may different based on the path.

Golang path/filepath Package Programs »





Comments and Discussions!

Load comments ↻





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