Cross Platform File Paths

Unlike with URLs which have a standardised format (they use forward-slashes to separate), file paths will differ between operating systems. This is mainly a historic issue, as it’s almost inconceivable to change them at this stage. This means Windows will use back-slashes and *nix systems use forward slashes.

This is a pain however when writing cross platform software because if you know a file exists in a folder, and want to get it’s contents, you will have to use it’s folder name, a slash and the file name. We can tackle this problem in a number of ways. Here are two quick ones:

package main

import (

func main() {

    // Make a cross-platform file
    // unix='dir/example' windows='dir\example'

    // Option 1
    examplePath := "dir" + string(os.PathSeparator) + "example"
    fmt.Println("PathSeparator: " + examplePath)

    // Option 2
    examplePath = filepath.FromSlash("dir/example")
    fmt.Println("FromSlash: " + examplePath)


Leave a Reply

Your email address will not be published. Required fields are marked *