I have found that there are lots of similar function in the package path and the package path/filepath. I have tried several common paths like /var/log/something
but did not find any differences. When should one use path
directly and when should one use filepath
instead?
What is the difference?
While functionally similar, path and path/filepath offer differing implementations. Filepath depends on the os package to choose the target runtime's file separators and other differing components when dealing with path strings.
You can look as the os source to see that there are differing implementations for various utility functions. This allows operating system specific details to be abstracted away by the library and helps achieve portability. The path/filepath dependency graph illustrates how the package depends upon the os package. You can compare this with the path dependency graph. I would encourage you to go into the filepath and path source code to observe this relationship.
When do I use each?
You should use filepath when working with files. This ensures your paths will be matched with actual files regardless of the underlying runtime. The path library should be used within models or when paths may be serialized or communicated with other programs. This ensures that a single formatting scheme is used regardless of what platform the programming is running on. Having a consistent format makes reasoning about models more generic and easier to understand.
Package path implements utility routines for manipulating slash-separated paths.
The path package should only be used for paths separated by forward slashes, such as the paths in URLs. This package does not deal with Windows paths with drive letters or backslashes; to manipulate operating system paths, use the path/filepath package.
Package filepath implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file paths.
The filepath package uses either forward slashes or backslashes, depending on the operating system. To process paths such as URLs that always use forward slashes regardless of the operating system, see the path package.
I find path/filepath
useful with Windows, as it handles Slash or Backslash,
while path
only handles Slash:
package main
import (
"path"
"path/filepath"
)
func main() {
{ // example 1
s := filepath.Dir(`C:\go\bin`)
println(s == `C:\go`)
}
{ // example 2
s := filepath.Dir("C:/go/bin")
println(s == `C:\go`)
}
{ // example 3
s := path.Dir("C:/go/bin")
println(s == "C:/go")
}
{ // example 4
s := path.Dir(`C:\go\bin`)
println(s == ".")
}
}
© 2022 - 2024 — McMap. All rights reserved.