Introduction

Hello again! In this lesson, we're revisiting Printf, an essential Go function for data printing. We'll explore it thoroughly to understand its critical role in formatting output. Let's get started!

Quick Recall: Printf Function

Do you remember the fmt package function, Printf? It serves as Go's tool for print formatting, akin to crafting a telling narrative with full control over the structure and direction. Allow me to provide a brief recap of Printf:

package main
import "fmt"
func main() {
    name := "John Doe"
    fmt.Printf("Hello, %s!\n", name)  // Hello, John Doe
}

In this Go code, %s acts as a string placeholder. Upon execution, Go replaces %s with the string stored in name.

Understanding the Syntax of Printf

Let's delve into Printf. Central to Printf are a format string and values. In essence, it is analogous to compiling words into a meaningful sentence.

x := 10
y := 20
fmt.Printf("x is %d and y is %d\n", x, y)  // x is 10 and y is 20

This example utilizes %d as a placeholder for an integer value. In the formatted print line, x and y replace %d correspondingly. Notice \n in the end of the string. It is a special character that creates a new line. Unlike fmt.Println, fmt.Printf function doesn't include a newline automatically. We will cover more details about special characters like this one in the following units.

Format Specifiers in Printf

Format specifiers in Printf orchestrate the display of various data types. Here's a summary:

  • %v: default format representation
  • %T: Go-syntax data type
  • %d: integer
  • %f: floating-point number
  • %s: string
  • %t: boolean

Let's see these specifiers in action:

x := 10
fmt.Printf("Type: %T, Value: %v\n", x, x) // Type: int, Value: 10

y := 20.5
fmt.Printf("Type: %T, Value: %f\n", y, y) // Type: float64, Value: 20.500000

name := "John Doe"
fmt.Printf("Type: %T, Value: %s\n", name, name) // Type: string, Value: John Doe

Choosing the appropriate specifier can render your code more efficient and precise, and less prone to errors.

Examples of Printf Usage

Now, let's demonstrate usage of Printf with different data types and precision control:

// Integer
fmt.Printf("Integer: %d\n", 10)  // Integer: 10

// Float
fmt.Printf("Float: %.2f\n", 12.3456)  // Float: 12.35

// String
fmt.Printf("String: %s\n", "Hello, world!")  // String: Hello, world!

// Boolean
fmt.Printf("Boolean: %t\n", true)  // Boolean: true

%.2f in a float denotes a floating-point number with precision up to 2 decimal places.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal