TheDeveloperBlog.com


Golang Fmt.Println: Console Programs

Fmt, printing. A program keeps some of its memory private. It does not need to tell us everything it does. But sometimes output needs to be printed and reported.


With fmt, a package included with Go, we display data to the console or another location. With classic methods like Printf and Println, fmt is easy to use.


Println. Let us begin with the Println method. This method is one of the easiest and simplest ones in fmt. We first must use an import statement with the argument "fmt."

Then: We invoke methods, like Println, on the fmt package. Println is versatile and can accept many arguments.

Tip: We can print values like strings or ints, or more complex things like slices. No loop is needed to print elements of a slice or array.

Based on:

Golang 1.4

Golang program that uses fmt, Println

package main

import "fmt"

func main() {
    // The Println method can handle one or more arguments.
    fmt.Println("cat")
    fmt.Println("cat", 900)

    // Use Println on a slice.
    items := []int{10, 20, 30}
    fmt.Println(items)
}

Output

cat
cat 900
[10 20 30]

Print, for-loop. The Println always inserts a newline after we use it. But Print does not: it just writes the data to the console with no trailing newline.

Tip: For loops where we want to display many things on a single line, Print is ideal.

Golang program that uses Print on slice

package main

import "fmt"

func main() {
    elements := []int{999, 99, 9}

    // Loop over the int slice and Print its elements.
    // ... No newline is inserted after Print.
    for i := 0; i < len(elements); i++ {
	fmt.Print(elements[i] + 1)
	fmt.Print(" ")
    }
    fmt.Println("... DONE!")
}

Output

1000 100 10 ... DONE!

Printf. This method accepts a format string. We use codes like "%s" and "%d" in this string to indicate insertion points for values. Those values are also passed as arguments.

Golang program that uses Printf

package main

import "fmt"

func main() {
    name := "Mittens"
    weight := 12

    // Use %s to mean string.
    // ... Use an explicit newline.
    fmt.Printf("The cat is named %s.\n", name)
    // Use %d to mean integer.
    fmt.Printf("Its weight is %d.\n", weight)
}

Output

The cat is named Mittens.
Its weight is 12.

Notes on fmt. Most programs in this Go tutorial use the import "fmt" statement. They are console programs, designed to be compiled and run directly.

Package fmt implements formatted IO with functions analogous to C's printf and scanf. The format 'verbs' are derived from C's but are simpler.

Fmt: golang.org

With methods prefixed by s, we can output the results to a string. We can write those strings to a file, or use them in any way we can use a string.