Golang: Cross-platform.

I would like to use path.Dir() on Unix and Windows with a specific directory on the platform. Please take a look at the code:

 package main import ( "fmt" "path" ) func main() { fmt.Println(`path.Dir("a/b/c"): `, path.Dir("a/b/c")) fmt.Println(`path.Dir("c:\foo\bar.exe"): `, path.Dir(`c:\foo\bar.exe`)) } 

Displays

 path.Dir("a/b/c"): a/b path.Dir("c:\foo\bar.exe"): . 

I would like to get a second call to path.Dir() (windows) something like

 c:\foo 

Is it possible to tell path.Dir() use Windows delimiters for my program running on Windows? Or do I always need to convert the backslash \ to slashes ( / )? What is your preferred strategy here?

+6
source share
1 answer

I see where the "problem" is. This discussion in golang-nuts told me that path.Dir() always uses / , and filepath.Dir() is a function that will be used for platform-specific manipulation.

 package main import ( "fmt" "path/filepath" ) func main() { fmt.Println(`filepath.Dir("a/b/c"): `, filepath.Dir("a/b/c")) fmt.Println(`filepath.Dir("c:\foo\bar.exe"): `, filepath.Dir(`c:\foo\bar.exe`)) } 

in the windows:

 filepath.Dir("a/b/c"): a\b filepath.Dir("c:\foo\bar.exe"): c:\foo 
+10
source

Source: https://habr.com/ru/post/923795/


All Articles