top of page
Writer's pictureRuud Wijnands

Rust String Formatting Tutorial - Part 1

Updated: Dec 29, 2024

This Rust tutorial describes the basic use and some more advanced uses of string formatting. The println! macro in Rust uses a syntax similar to Python’s string formatting, enabling flexible and powerful ways to format strings. Here's an overview of the formatting options available in Rust:


Basic Syntax

The placeholders for formatting are enclosed in {} within the string. The macro replaces these placeholders with the provided values.

println!("Hello, {}!", "world"); // Hello, world!

Positional and Named Arguments

  • Positional arguments: Placeholders can specify arguments by their index.

println!("{0}, {1}, {0} again!", "Hello", "world"); // Hello, world, Hello again!
  • Named arguments: Arguments can also be referenced by name.

println!("{greeting}, {name}!", greeting="Hello", name="world"); // Hello, world!

Formatting Options

Inside {}, you can specify additional options after a colon (:). These options include alignment, width, precision, and more.


Alignment

Specifies how the value should be aligned within the field.

  • Left-align (:<)

println!("{:<6}", "Hi"); // "Hi "
  • Right-align (:>):

println!("{:>6}", "Hi"); // " Hi"
  • Center-align (:^):

println!("{:^6}", "Hi"); // " Hi "

Width

Sets the minimum width of the field. If the value is shorter than the specified width, it is padded with spaces (by default).

println!("{:6}", "Hi"); // "Hi    " (padded to a width of 6)

Fill Character

Specify a character for padding.

println!("{:*<6}", "Hi"); // "Hi****"
println!("{:*^6}", "Hi"); // "**Hi**"
println!("{:*>6}", "Hi"); // "****Hi"

Precision

For floating-point numbers, precision limits the number of digits after the decimal point.

println!("{:.2}", 3.14159); // "3.14"

For strings, precision limits the number of characters displayed.

println!("{:.4}", "Hello, world!"); // "Hell"

Combining Width and Precision

println!("{:6.2}", 3.14159); // "  3.14" (width 6, precision 2)

Signs

Control the display of signs for numeric values.

  • Always show a sign (:+):

println!("{:+}", 42); // "+42" println!("{:+}", -42); // "-42"
  • Display a space for positive numbers (: ):

println!("{: }", 42); // " 42" println!("{: }", -42); // "-42"

Number Formatting

  • Binary (:b):

println!("{:b}", 42); // "101010"
  • Octal (:o):

println!("{:o}", 42); // "52"
  • Hexadecimal (:x / :X):

println!("{:x}", 42); // "2a" println!("{:X}", 42); // "2A"
  • Debug (:?): For printing debug representations of values (like structs or enums).

println!("{:?}", (42, "Hello")); // "(42, \"Hello\")"

Zero Padding

Pads the number with zeros instead of spaces.

println!("{:06}", 42); // "000042"

Advanced: Custom Types

To use println! formatting with custom types, implement the std::fmt::Display or std::fmt::Debug traits for your type.

use std::fmt;

struct Point {
    x: i32,
    y: i32,
}

impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "({}, {})", self.x, self.y)
    }
}

let point = Point { x: 1, y: 2 };
println!("{}", point); // "(1, 2)"

Example Combining Features

println!("{:<8} | {:^8} | {:>8}", "left", "center", "right");
// "left     |  center  |    right"

println!("{:*>8.2}", 3.14159); // "***3.14"

Summary Table

Format Specifier

Description

:<

Left-align the value within the width

:>

Right-align the value within the width

:^

Center-align the value within the width

:<width>

Specify minimum width

:<fill><align>

Specify fill character and alignment

:.<precision>

Set precision for floats or limit string length

:+

Always show a sign for numbers

:

Show a space for positive numbers

:b

Binary format

:o

Octal format

:x/:X

Hexadecimal (lowercase/uppercase)

:?

Debug representation

:06

Zero-padded to width 6

This flexibility allows println! to handle a wide range of formatting needs!

8 views0 comments

Recent Posts

See All

Comments


bottom of page