Series: Go

fmt Package in Go

Master the fmt package in Go and craft elegant, expressive code. Learn Printf, Scanf, Sprintf, and more to transform your Go programming.
E
Edtoks21:42 min read

The fmt package in Go provides functionality for formatting and printing text. It is an essential package used for input and output operations in Go programs. Whether you're printing to the console, formatting strings, or reading input, the fmt package is your go-to tool.

Placeholder or Format Specifier

Format specifiers in the fmt package are placeholders in the format string that define how the subsequent values should be formatted. They are verbs represented by characters like %d, %s, %f, etc. Each specifier corresponds to a specific data type, and it instructs the fmt package on how to format the values.

Format Specifiers

package main
import "fmt"

func main() {
    name := "Alice"
    age := 25
    // %s is a specifier for a string, and %d is a specifier for an integer
    fmt.Printf("Name: %s, Age: %d\n", name, age)
}

Output is
Name: Alice, Age: 25

In this example, %s is used to format the string variable name, and %d is used for the integer variable age. The values are substituted into the format string during printing.

Precision and Width

In the fmt package in Go, precision and width are formatting options that allow you to control the appearance of numeric and string values when printed. These options are specified as part of the format specifier and are denoted by numbers following the % character. Understanding precision and width is crucial for formatting output according to specific requirements.

Width

  • Definition: Width specifies the minimum width of the field. It ensures that the output is padded with spaces (on the left or right) to meet the specified width.

  • Format: %[width]specifier

package main
import "fmt"

func main() { value := 42 // %5d specifies a minimum width of 5 for the integer fmt.Printf("Value: %5d\n", value) }

Output is

Value:    42

In this example, %5d specifies that the integer value should be printed in a field at least 5 characters wide. If the value is less than 5 characters, it will be padded with spaces on the left.

Precision

  • Definition: Precision is the maximum number of digits (for numeric types) or characters (for strings) to be printed. For floating-point numbers, precision specifies the number of digits after the decimal point.

  • Format: %.[precision]specifier

package main
import "fmt"

func main() { pi := 3.14159265359 // %.2f specifies two decimal places for the floating-point number fmt.Printf("Value of Pi: %.2f\n", pi) }

Output is

Value of Pi: 3.14

Here, %.2f specifies that the floating-point value should be printed with two digits after the decimal point.

Combining Width and Precision

You can combine width and precision to achieve more precise formatting.

package main
import "fmt"

func main() { text := "Hello" // %8.3s specifies a minimum width of 8 and a maximum of 3 characters for the string fmt.Printf("Text: %8.3s\n", text) }

Output is

Text:      Hel

In this example, %8.3s specifies a minimum width of 8 for the string and a maximum of 3 characters. If the string is longer than 3 characters, it will be truncated; if it's shorter, it will be padded with spaces on the left.

Understanding and using width and precision allows you to format output according to specific layout requirements, making your printed output more readable and aesthetically pleasing.

Advanced Format Specifiers

package main
import "fmt"
type Person struct {
    FirstName string
     LastName  string
}
func main() { person := Person{FirstName: "John", LastName: "Doe"} // %+v specifies a detailed printout of a struct, including field names fmt.Printf("Person: %+v\n", person) }

Output is

Person: {FirstName:John LastName:Doe}

In this example, %+v is a specifier for a detailed printout of a struct, including field names. This is useful for debugging and providing a comprehensive view of the struct.

Understanding format specifiers in the fmt package is essential for controlling the output of your Go programs. Whether you're formatting strings, integers, or complex data structures, using the appropriate specifiers ensures precision and clarity in your printed output. As you advance, explore additional specifiers and their nuances to become a proficient user of the fmt package.

Printing to the Console with fmt

Printing to the console in Go is accomplished using the fmt package, which provides three main functions for this purpose: Print, Println, and Printf. Each function has its specific use case and formatting options. Let's explore each of them with examples.

The Print function is used to print values to the standard output without adding a newline at the end.

package main
import "fmt"

func main() { name := "Alice" age := 25 // Print without newline fmt.Print("Name: ", name, ", Age: ", age) fmt.Print(" - This is on the same line.") }

Output is

Name: Alice, Age: 25 - This is on the same line.

In this example, Print is used to print the name and age without adding a newline. Subsequent Print calls append to the same line.

Println Function

The Println function is similar to Print but adds a newline at the end, making it suitable for separate lines of output.

package main
import "fmt"

func main() { name := "Bob" age := 30 // Println adds a newline fmt.Println("Name:", name) fmt.Println("Age:", age) fmt.Println("This is on a new line.") }

Output is

Name: Bob
Age: 30
This is on a new line.

Here, Println is used to print the name and age on separate lines, and each call starts a new line of output.

Printf Function

The Printf function allows formatted printing using format specifiers. It is powerful for controlling the appearance of values.

package main
import "fmt"

func main() { name := "Bob" age := 30 // Println adds a newline fmt.Printf("Name: %s\n", name) fmt.Printf("Age: %d\n", age) fmt.Printf("This is on a new line.") }

Output is

Name: Bob
Age: 30
This is on a new line.

In this example, Printf is used to print a formatted string with a product name and price, specifying two decimal places for the floating-point number.

The fmt package provides flexible functions for printing to the console in Go. Whether you need a simple print, newline-separated lines, or precise formatted output, Print, Println, and Printf cover a wide range of use cases. Understanding these functions and their formatting options is essential for effective console output in your Go programs.

Reading from the Console with fmt

Reading from the console in Go is achieved using the fmt package, primarily through the Scan, Scanln, and Scanf functions. These functions allow you to capture user input during program execution. Let's explore each of them with examples, ranging from beginner to expert levels.

Scan Function

The Scan function reads user input from the standard input (console) and stores the values in variables.

package main
import "fmt"
func main() { var name string // Prompt the user and read input fmt.Print("Enter your name:") fmt.Scan(&name) // Print the entered name fmt.Println("Hello, ", name) }

Output is

Enter your name:Rabbani
Hello,  Rabbani

In this example, Scan is used to read a string from the console, and the entered name is then printed.

Scanln Function

The Scanln function is similar to Scan but reads the entire line until a newline character, making it suitable for reading multiple values.

package main
import "fmt"

func main() { var age int var city string // Prompt the user and read input for age and city fmt.Print("Enter your age and city (space-separated): ") fmt.Scanln(&age, &city)// Print the entered age and city fmt.Println("Age:", age) fmt.Println("City:", city) }

Output is

Enter your age and city (space-separated): 30 Bangalore
Age: 30
City: Bangalore

Here, Scanln reads both age and city from the same line of input, separated by a space.

Scanf Function

The Scanf function allows formatted input, similar to Printf. It provides more control over the input format using format specifiers.

package main
import "fmt"

func main() {
    var width float64
    var height float64
    // Prompt the user and read input with specific format
    fmt.Print("Enter width and height (comma-separated): ")
    fmt.Scanf("%f,%f", &width, &height)// Calculate and print the area
    area := width * height
    fmt.Printf("Area: %.2f\n", area)
}

Output is

Enter width and height (comma-separated): 10,20
Area: 200.00

In this example, Scanf is used to read two floating-point values separated by a comma and then calculates and prints the area.

The Scan, Scanln, and Scanf functions in the fmt package enable interactive user input in Go programs. From simple single-value reads to formatted input, these functions cater to various input scenarios. Understanding their usage and incorporating them into your programs enhances the interactivity and functionality of your Go applications.

Writing to a File with fmt

Writing to a file in Go is accomplished using the fmt package in combination with the os package for file handling. Three main functions in the fmt package facilitate this process: FPrint, FPrintln, and FPrintf. Each function has its specific use case for writing formatted data to a file. Let's explore these functions with examples, covering beginner to expert levels.

Fprint Function

The Fprint function is used to write values to a file without adding a newline at the end.

package main
import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Create("output.txt")
    if err != nil {
		fmt.Println("Error creating file: ", err)
		return
    }
    defer file.Close()
     name := "Alice"
    age := 25
    // Write to file without newline
    fmt.Fprint(file, "Name: ", name, ", Age: ", age)
}
Check output.txt file
#cat output.txt
Name: Alice, Age: 25

In this example, the Fprint function is used to write the name and age to a file without adding a newline.

Fprintln Function

The Fprintln function is similar to Fprint but adds a newline at the end, making it suitable for separate lines of output.

package main
import ( 
    "fmt"
    "os"
)

func main() {
    file, err := os.Create("output.txt")
    if err != nil {
        fmt.Println("Error creating file:", err)
        return
    }
    defer file.Close()

    name := "Bob" 
    age := 30
    // Write to file with newline
    fmt.Fprintln(file, "Name:", name)
    fmt.Fprintln(file, "Age:", age)
}

Check output.txt file

#cat output.txt
Name: Bob
Age: 30

Here, Fprintln is used to write the name and age on separate lines in the file.

Fprintf Function

The Fprintf function allows formatted writing using format specifiers, similar to Printf.

package main                                                                                          
import (
"fmt"
"os"
)
                                                                                                      
func main() {
    file, err := os.Create("output.txt")
    if err != nil {
        fmt.Println("Error creating file:", err)
        return
    }
    defer file.Close()

    price := 49.99
    // Write formatted string to file
    fmt.Fprintf(file, "Product: %s, Price: $%.2f\n", "Widget", price)
}

Check output.txt file

#cat output.txt
Product: Widget, Price: $49.99

In this example, Fprintf is used to write a formatted string with a product name and price to the file, specifying two decimal places for the floating-point number.

The Fprint, Fprintln, and Fprintf functions in the fmt package, when used in conjunction with the os package for file handling, provide a convenient way to write formatted data to a file in Go. Whether you need to write simple values, lines, or formatted strings, these functions cover a wide range of file writing scenarios. Understanding their usage is essential for effective file output in your Go programs.

Reading from a File with fmt

Reading from a file in Go is typically done using the fmt package in conjunction with the os package for file handling. Three main functions in the fmt package, namely Fscan, Fscanln, and Fscanf, assist in reading formatted data from a file. Let's explore these functions with examples, covering beginner to expert levels.

Fscan Function

The FScan function reads formatted data from a file and stores it in variables.

Create a file input.txt with the contents Rabbani 44

package main
import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Open("input.txt")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    var name string
    var age int// Read from file using FScan
    fmt.Fscan(file, &name, &age)// Print the read values
    fmt.Println("Name:", name)
    fmt.Println("Age:", age)
}

Output is

Name: Rabbani
Age: 25

In this example, Fscan reads a string and an integer from the file and prints the read values.

Fscanln Function

The Fscanln function is similar to Fscan but reads the entire line until a newline character, making it suitable for reading multiple values from a line.

Create a file input.txt with the contents Rabbani 44 Bangalore

package main
import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Open("input.txt")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    var name string
    var age int// Read from file using FScan
    var city string
    fmt.Fscanln(file, &name, &age, &city)// Print the read values
    fmt.Println("Name:", name)
    fmt.Println("Age:", age)
    fmt.Println("City:", city)
}

Output is

Name: Rabbani
Age: 25
City: Bangalore

Here, FScanln reads both age and city from the same line of the file, separated by a space.

Fscanf Function

The Fscanf function allows formatted input using format specifiers, similar to Scanf. It provides more control over the input format.

Create a file input.txt with the contents 45.235,12.786

package main
import (
    "fmt"
    "os"
)

func main() {
    file, err := os.Open("input.txt")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    var width float64
    var height float64// Read from file using FScanf
    fmt.Fscanf(file, "%f,%f", &width, &height)// Calculate and print the area
    area := width * height
    fmt.Printf("Width: %.2f\n", width)
    fmt.Printf("Height: %.2f\n", height)
    fmt.Printf("Area: %.2f\n", area)
}

Outout is

Width: 45.23
Height: 12.79
Area: 578.37

In this example, FScanf reads two floating-point values separated by a comma from the file and calculates and prints the area.

The Fscan, Fscanln, and Fscanf functions in the fmt package, when used with the os package for file handling, provide a convenient way to read formatted data from a file in Go. Whether you need to read simple values, lines, or formatted strings, these functions cover a variety of file reading scenarios. Understanding their usage is essential for effective file input in your Go programs.

Printing to a String instead of Console with fmt

Printing to a string in Go is achieved using the fmt package, which provides three main functions for this purpose: Sprint, Sprintln, and Sprintf. These functions allow you to format and concatenate values into a string. Let's explore each of them with examples, covering beginner to expert levels.

Sprint Function

The SPrint function is used to concatenate values into a string without adding a newline at the end.

package main
import "fmt"

func main() {
    name := "Alice"
    age := 25
    
    // Concatenate values into a string
    result := fmt.Sprint("Name: ", name, ", Age: ", age)

    // Print the result
    fmt.Println(result)
}

Output is

Name: Alice, Age: 25

In this example, Sprint is used to concatenate the name and age into a string, and the result is then printed.

Sprintln Function

The Sprintln function is similar to Sprint but adds a newline at the end, making it suitable for separate lines of output.

 

package main
import "fmt"

func main() {
    name := "Rabbani"
    age := 44
    
    // Concatenate values into a string
    result := fmt.Sprintln("Name: ", name, ", Age: ", age)

    // Print the result
    fmt.Println(result)
}

Output is

Name:  Rabbani , Age:  44


Here, Sprintln is used to concatenate the name and age into a string, with each value on a new line.

Sprintf Function

The SPrintf function allows formatted concatenation using format specifiers, similar to Printf.

package main
import "fmt"

func main() {
    price := 49.99

    // Concatenate formatted string
    result := fmt.Sprintf("Product: %s, Price: $%.2f\n", "Widget", price)

    // Print the result
    fmt.Print(result)
}

Output is

Product: Widget, Price: $49.99

In this example, Sprintf is used to concatenate a formatted string with a product name and price into a string.

The Sprint, Sprintln, and Sprintf functions in the fmt package provide a convenient way to concatenate values into a string in Go. Whether you need simple concatenation, newline-separated lines, or formatted strings, these functions cover a variety of use cases. Understanding their usage is essential for effective string manipulation in your Go programs.

Reading from a String with fmt

Reading from a string in Go is accomplished using the fmt package, which provides three main functions for this purpose: Sscan, Sscanln, and Sscanf. These functions allow you to parse values from a string. Let's explore each of them with examples, covering beginner to expert levels.

Sscan Function

The Sscan function reads formatted data from a string and stores it in variables.

package main
import ("fmt")

func main() {
    input := "Alice 25"
    var name string
    var age int

    // Read from string using Sscan
    n, err := fmt.Sscan(input, &name, &age)
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    // Print the read values
    fmt.Printf("%d values read. Name: %s, Age: %d\n", n, name, age)
}

Output is

2 values read. Name: Alice, Age: 25

In this example, Sscan reads a string and parses a name and an age from it, printing the read values.

Sscanln Function

The Sscanln function is similar to Sscan but reads the entire line until a newline character, making it suitable for reading multiple values from a line.

package main

import (
	"fmt"
)

func main() {
	// Sample input string
	inputString := "John 25 175.5 true"

	// Declare variables to store values
	var name string
	var age int
	var height float64
	var isStudent bool

	// Use fmt.Sscanln to read values from the input string
	num, err := fmt.Sscanln(inputString, &name, &age, &height, &isStudent)

	// Check for errors
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	// Print the values
	fmt.Println("Number of items successfully scanned:", num)
	fmt.Println("Name:", name)
	fmt.Println("Age:", age)
	fmt.Println("Height:", height)
	fmt.Println("Is Student:", isStudent)
}

Output is

Number of items successfully scanned: 4
Name: John
Age: 25
Height: 175.5
Is Student: true

Here, Sscanln reads both age and city from the same line of the string, separated by a space.

Sscanf Function

The Sscanf function allows formatted parsing using format specifiers, similar to Scanf. It provides more control over the input format.

package main

import (
	"fmt"
)

func main() {
	// Sample input string
	inputString := "John 25 175.5 true"

	// Declare variables to store values
	var name string
	var age int
	var height float64
	var isStudent bool

	// Use fmt.Sscanf to read values from the input string
	num, err := fmt.Sscanf(inputString, "%s %d %f %t", &name, &age, &height, &isStudent)

	// Check for errors
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	// Print the values
	fmt.Println("Number of items successfully scanned:", num)
	fmt.Println("Name:", name)
	fmt.Println("Age:", age)
	fmt.Println("Height:", height)
	fmt.Println("Is Student:", isStudent)
}

Output is

Number of items successfully scanned: 4
Name: John
Age: 25
Height: 175.5
Is Student: true

In this example, Sscanf reads two floating-point values separated by spaces from the string and calculates and prints the area.

The Sscan, Sscanln, and Sscanf functions in the fmt package provide a convenient way to parse values from a string in Go. Whether you need to read simple values, lines, or formatted strings, these functions cover various string parsing scenarios. Understanding their usage is essential for effective string manipulation in your Go programs.

Formatting and Error Handling

The Errorf function formats a string and returns it as an error.

Example:

package main
import (
    "fmt"
//    "errors"
)

func divide(a, b int) (int, error) {
    if b == 0 {
        return 0, fmt.Errorf("cannot divide by zero")
    }
    return a / b, nil
}

func main() {
    result, err := divide(10, 2)
    if  err != nil {
        fmt.Println("Error:", err)
        return
    }
    fmt.Println("Result:", result)

    result, err = divide(20, 0)
    if  err != nil {
        fmt.Println("Error:", err)
        return
    }

    fmt.Println("Result:", result)
}

Output is

Result: 5
Error: cannot divide by zero

In this example, the Errorf function is used to create a formatted error message when attempting to divide by zero.

Conclusion

The fmt package in Go is a powerful tool for formatting and printing text. Whether you're printing to the console, formatting strings, or writing to files, the functions provided by the fmt package offer flexibility and ease of use. Understanding the format string syntax and various verbs enables you to control the output precisely. Use the fmt package to make your Go programs more expressive and user-friendly.

Reference

There are other functions supported by fmt package in Go. Refer Go fmt package for more details.