File Paths
This Go code demonstrates various functions from the filepath
package for working with file paths. Let's go through the code with inline comments and explanations:
Output
Explanation:
Joining Paths:
filepath.Join("dir1", "dir2", "filename")
joins path elements to form a path.
Handling Extra Separators:
filepath.Join("dir1//", "filename")
demonstrates joining with extra separators.filepath.Join("dir1/../dir1", "filename")
resolves ".." in the path.
Extracting Directory and Base Name:
filepath.Dir(p)
extracts the directory from the path.filepath.Base(p)
extracts the base name (filename) from the path.
Checking if Path is Absolute:
filepath.IsAbs("dir/file")
checks if the path is absolute (false).filepath.IsAbs("/dir/file")
checks if the path is absolute (true).
Extracting Extension:
filepath.Ext(filename)
extracts the extension from a filename.
Trimming Suffix:
strings.TrimSuffix(filename, ext)
removes the extension from a filename.
Relative Paths:
filepath.Rel("a/b", "a/b/t/file")
finds the relative path between two paths.filepath.Rel("a/b", "a/c/t/file")
demonstrates handling a case where the paths are not relative.
Last updated
Was this helpful?