本文最后更新于 2024-03-22,本文发布时间距今超过 90 天, 文章内容可能已经过时。最新内容请以官方内容为准

Differences between rust format marco

In Rust, the format_args! macro and the format! macro are both used for formatting strings, but they have some key differences in their usage.

  1. format_args! Macro:

    • The format_args! macro is used to create an instance of std::fmt::Arguments type, which contains all the information required for formatting.
    • It is typically used when you need to save the formatted data for later, rather than outputting it immediately, or when you need to pass the formatted data to a function that expects to receive an Arguments type.
    • Using format_args! macro does not perform the string formatting directly but generates an object containing the formatting information, which can be used by the std::fmt::format function or other functions that accept an Arguments type parameter.

    Example:

    use std::fmt;
    let args = format_args!("Hello, {}!", "world");
    let s = fmt::format(args);
    assert_eq!(s, "Hello, world!");
    
  2. format! Macro:

    • The format! macro is a convenience wrapper for format_args!, which uses the format_args! macro internally to create Arguments instances and then immediately uses the std::fmt::format function to convert these arguments into a String.
    • It directly generates the final formatted string, usually used when you need to immediately create and use the formatted string.
    • The format! macro is more concise because it eliminates the step of manually calling the format function.

    Example:

    let s = format!("Hello, {}!", "world");
    assert_eq!(s, "Hello, world!");
    

Summary

  • In summary, the format_args! macro provides more flexibility, allowing you to create an instance of formatted arguments and use it when needed, while the format! macro offers a quick and convenient way to generate a formatted string. In most cases, if your goal is to generate a formatted string directly, using format! macro is more straightforward. If you need more granular control over the formatting process or need to pass the formatted data to other functions, format_args! macro is a better choice.

  • Expanding on this, it’s worth noting that the format! macro is so commonly used that it is often preferred for its simplicity and ease of use. It is the preferred method for most formatting tasks in Rust, as it combines the power of pattern matching with the convenience of immediate string creation. This makes it an excellent choice for a wide range of applications, from simple string substitutions to complex data formatting tasks.

  • Additionally, the format! macro is also capable of handling many edge cases and special scenarios, such as formatting references, slices, and other complex data structures. This flexibility, combined with its ease of use, makes it a powerful tool for any Rust programmer.