What is the most portable/cross-platform way to represent a newline in go/golang?

后端 未结 3 1431
深忆病人
深忆病人 2020-12-30 20:24

Currently, to represent a newline in go programs, I use \\n. For example:

package main

import \"fmt\"


func main() {
    fmt.Printf(\"%d is %s         


        
3条回答
  •  余生分开走
    2020-12-30 20:45

    You can always use an OS specific file to declare certain constants. Just like _test.go files are only used when doing go test, the _[os].go are only included when building to that target platform.

    Basically you'll need to add the following files:

     - main.go
     - main_darwin.go     // Mac OSX
     - main_windows.go    // Windows
     - main_linux.go      // Linux
    

    You can declare a LineBreak constant in each of the main_[os].go files and have your logic in main.go.

    The contents of you files would look something like this:

    main_darwin.go

    package somepkg
    
    const LineBreak = "\n"
    

    main_linux.go

    package somepkg
    
    const LineBreak = "\n"
    

    main_windows.go

    package somepkg
    
    const LineBreak = "\r\n"
    

    and simply in your main.go file, write the code and refer to LineBreak

    main.go

    package main
    
    import "fmt"
    
    
    func main() {
        fmt.Printf("%d is %s %s", 'U', string(85), LineBreak)
    }
    

提交回复
热议问题