Variants of Formatting methods in Go

Learn how fmt methods behave differently

func main() {
  fmt.Print("Print --> I don't add a new line")
  fmt.Println()
  fmt.Println("Println --> I do add a new line")
  fmt.Printf("Printf --> With the help of formatting verbs, I welcome dynamic variables, like %d\n", 5)
  // The following line will emit a warning: result of fmt.Sprintf call not used
  // fmt.Sprint("Sprint --> I don't print my static value to standard output")

  s := fmt.Sprint("Sprint --> I don't print my static value to standard output")
  fmt.Println(s)
  sf := fmt.Sprintf("SPrintf --> I don't print my dynamic value to standard output either, so you need to assign me to a variable first, then %d ", 5)
  fmt.Println(sf)
}

The output of the above code looks like this:

Print --> I don't add a new line
Println --> I do add a new line
Printf --> With the help of formatting verbs, I welcome dynamic variables, like 5
Sprint --> I don't print my static value to standard output
SPrintf --> I don't print my dynamic value to standard output either, so you need to assign me to a 5 first

To make it sound more formal:

  • fmt.Print writes to the standard output, without a new line at the end.

  • fmt.Println writes to the standard output (usually the console) and appends a newline character at the end. It takes a variable number of arguments and formats them using their default formatting.

  • fmt.Printf is similar to fmt.Println, but it allows you to specify a custom format string. The syntax for a format string is %[flags][width][.precision]verb, where verb specifies the type of the argument (e.g. d for integers, f for floating-point numbers).

  • fmt.Sprint formats its arguments and returns the resulting string, rather than printing it to the standard output.

  • fmt.Sprintf is similar to fmt.Sprint, but it allows you to specify a custom format string.