golang判断两路径是不是同一卷
在Go语言中,可以使用filepath.VolumeName函数获取给定路径的卷名,然后比较两个路径的卷名是否相同来判断它们是否在同一卷上。
例如:
package main
import (
"fmt"
"path/filepath"
)
func main() {
path1 := "C:\\Users\\test\\file.txt"
path2 := "D:\\file.txt"
fmt.Printf("Path1 and Path2 are on the same volume: %v\n", isSameVolume(path1, path2))
path3 := "C:\\Users\\test\\file.txt"
path4 := "C:\\Users\\test\\folder\\file.txt"
fmt.Printf("Path3 and Path4 are on the same volume: %v\n", isSameVolume(path3, path4))
}
func isSameVolume(path1, path2 string) bool {
vol1 := filepath.VolumeName(path1)
vol2 := filepath.VolumeName(path2)
return vol1 == vol2
}
输出结果为:
Path1 and Path2 are on the same volume: false
Path3 and Path4 are on the same volume: true
可以看到,第一组路径不在同一卷上,而第二组路径在同一卷上。
原文地址: http://www.cveoy.top/t/topic/6o0 著作权归作者所有。请勿转载和采集!