Reputation: 7805
I need to extract the name first of the first directory in a relative path.
I know I can go about:
relPath := "a/b/c/file.so"
splitPath := strings.Split(relPath, string(os.PathSeparator))
rootDirName := splitPath[0]
Is there a better way?
Upvotes: 2
Views: 479
Reputation: 881
If you're asking whether there is way to do it with 1 standard Go function: not that I know of.
An alternative way would be:
relPath := "a/b/c/file.so"
i := strings.Index(relPath, string(os.PathSeparator))
rootDirName := relPath[:i]
Or if it is possible that the path contains no /
at all:
relPath := "a/b/c/file.so"
i := strings.Index(relPath, string(os.PathSeparator))
rootDirName := ""
if i != -1 {
rootDirName = relPath[:i]
}
This has the benefit of not having to split the whole string and might, therefore, be a little faster on long paths.
Upvotes: 3