Standard library / path/filepath

path/filepath.Rel()

Computes a lexical path from base to target; can return dot-dot elements and may fail for incompatible roots. Example uses a disposable temporary workspace. Expected stdout: '../assets/logo.svg\n'.

Formal Syntax & Structure

go syntaxgo
func Rel(basepath, targpath string) (string, error)

Parameters & Attributes

NameTypeDescription
basepathstringBase path for relative calculation.
targpathstringTarget path.

Return Value

(string, error)

Computes a lexical path from base to target; can return dot-dot elements and may fail for incompatible roots.

Working Example

Example Snippetgo
package main
import (  "fmt"  "os"  "path/filepath")
func check(e error) {  if e != nil {    panic(e)  }}func workspace() func() {  root, e := os.MkdirTemp("", "bytemind-go-")  check(e)  old, e := os.Getwd()  check(e)  check(os.Chdir(root))  return func() { check(os.Chdir(old)); check(os.RemoveAll(root)) }}func main() {  defer workspace()()  p, e := filepath.Rel("docs", "assets/logo.svg")  check(e)  fmt.Println(filepath.ToSlash(p))}
Go Reference