Behavior of Go print functions
This page exists because:
- I've been using this language for more than a decade and still can't remember this.
- The documentation is full of annoying "x is like y" redirects.
- Just using
Printfeverywhere feels like a cop-out.
|log.Print||no||yes||…in the manner of fmt.Print|
|log.Fatal||no||yes||…equivalent to Print() followed by a call to os.Exit(1)|
|log.Panic||no||yes||…equivalent to Print() followed by a call to panic()|
|log.Println||yes||yes||…in the manner of fmt.Println|
|log.Fatalln||yes||yes||…equivalent to Println() followed by a call to os.Exit(1)|
|log.Panicln||yes||yes||…equivalent to Println() followed by a call to panic()|
|testing.T.Log||yes||yes||…analogous to Println|
|testing.T.Error||yes||yes||…equivalent to Log followed by Fail|
|testing.T.Fatal||yes||yes||…equivalent to Log followed by FailNow|
"Spaces" describes whether spaces are always added between operands, or only when neither is a string.
"Newline" describes whether a trailing newline is added.
lnfunctions add spaces and a trailing newline.
lnfunctions don't add spaces or a trailing newline.
So you should write code like this:
fmt.Println("Something failed:", err) fmt.Fprintln(os.Stderr, "Something failed:", err)
log functions always add newlines, even for the non-
ln versions. So you
log.Print("Something failed: ", err) log.Fatal("Something failed: ", err)
Or (at the expense of an additional character):
log.Println("Something failed:", err) log.Fatalln("Something failed:", err)
testing functions always add spaces and append newlines, despite not having
in their names. So write:
t.Error("Something failed:", err) t.Fatal("Something failed:", err)
There's always Go 2, I guess.