Learning Golang: Println and Print

Share on:

This is part 15 of my journey learning Golang.

fmt Package

Go’s fmt package implements formatted I/O with formatting functions in the venerable, old-school style of the C language, but modernized.

This article covers the most basic functions for printing out text Println and Print:

Println

The Println method prints outs a line of text to the standard output device.

It prints its arguments, with a space between them, and a new line character at the end.

For example, this program:

1package main
2
3import "fmt"
4
5func main() {
6  fmt.Println("Line", 1)
7  fmt.Println("This", "is", "line", 2)
8  fmt.Println("End")
9}

prints out:

1Line 1
2This is line 2
3End

Print

The Print method prints out its arguments without adding spaces in between. It also doesn’t add a new line character.

For instance this program:

 1package main
 2
 3import "fmt"
 4
 5func main() {
 6  points := 25750
 7  rating := "HIGH SCORE!"
 8  fmt.Print("Your points", ": ")
 9  fmt.Print(points)
10  fmt.Print(" (", rating, ")")
11}

prints out:

1Your points: 25750 (HIGH SCORE!)

Notice how the spaces are embedded in the arguments. Also, a line break was not added at the end. The next output would continue on the same line.


comments powered by Disqus