Go Output
Go's fmt package provides simple, flexible tools for printing and formatting output, including Println, Printf, and Sprintf.
Printing with fmt.Println
fmt.Println prints one or more values to the console, separates them with spaces, and adds a newline at the end automatically.
Using fmt.Println
package main
import "fmt"
func main() {
fmt.Println("Go", "makes", "printing", "easy")
}Formatted Output with fmt.Printf
fmt.Printf lets you build a formatted string using verbs, special placeholders starting with %, and does not add a newline automatically. Common verbs include %s for strings, %d for integers, %f for floats, and %v for any value's default representation.
Using fmt.Printf
package main
import "fmt"
func main() {
name := "Maria"
age := 29
fmt.Printf("%s is %d years old\n", name, age)
}Building Strings with fmt.Sprintf
fmt.Sprintf works exactly like Printf, but instead of printing to the console it returns the formatted text as a string, which you can store in a variable and use later.
Using fmt.Sprintf
package main
import "fmt"
func main() {
name := "Maria"
age := 29
summary := fmt.Sprintf("%s is %d years old", name, age)
fmt.Println(summary)
}- fmt.Print — writes values with no automatic spacing or newline
- fmt.Println — writes values separated by spaces, then a newline
- fmt.Printf — writes a formatted string using verbs, no automatic newline
- fmt.Sprintf — returns a formatted string instead of printing it
- fmt.Sprintln — returns values joined with spaces and a trailing newline
Exercise: Go Output
Which package must be imported to print output to the console?