Toggle theme

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 Printf everywhere feels like a cop-out.
Function Spaces Newline Documentation
fmt.Print no no
fmt.Fprint no no
fmt.Sprint no no
fmt.Println yes yes
fmt.Fprintln yes yes
fmt.Sprintln yes yes
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.

To summarize:

  • ln functions add spaces and a trailing newline.
  • Non-ln functions 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)

Except the log functions always add newlines, even for the non-ln versions. So you can write:

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)

Except the testing functions always add spaces and append newlines, despite not having ln in their names. So write:

t.Error("Something failed:", err)
t.Fatal("Something failed:", err)

There's always Go 2, I guess.