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

倖福魔咒の 提交于 2019-11-29 10:54:19

问题


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

package main

import "fmt"


func main() {
    fmt.Printf("%d is %s \n", 'U', string(85))
}

... will yield 85 is U followed by a newline.

However, this doesn't seem all that cross-platform. Looking at other languages, PHP represents this with a global constant ( PHP_EOL ). Is \n the right way to represent newlines in a cross-platform specific manner in go / golang?


回答1:


I got curious about this so decided to see what exactly is done by fmt.Println. http://golang.org/src/pkg/fmt/print.go

If you scroll to the very bottom, you'll see an if addnewline where \n is always used. I can't hardly speak for if this is the most "cross-platform" way of doing it, and go was originally tied to linux in the early days, but that's where it is for the std lib.

I was originally going to suggest just using fmt.Fprintln and this might still be valid as if the current functionality isn't appropriate, a bug could be filed and then the code would simply need to be compiled with the latest Go toolchain.




回答2:


Having the OS determine what the newline character is happens in many contexts to be wrong. What you are really want to know is what the "record" seperator is and Go assumes that you as the programmer should know that.

Even if the binary runs on windows it may be consuming a file from a Unix OS.

Line endings are determined by what the source of the file or document said was a line ending not the OS the binary is running in.




回答3:


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)
}


来源:https://stackoverflow.com/questions/14493867/what-is-the-most-portable-cross-platform-way-to-represent-a-newline-in-go-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!