Why can't fmt::Arguments be safely generated at runtime?

Viewed 113

The documentation for core::fmt::Arguments states:

This structure represents a safely precompiled version of a format string and its arguments. This cannot be generated at runtime because it cannot safely be done, so no constructors are given and the fields are private to prevent modification.

Exactly what is it about generating such a structure at runtime that cannot safely be done?

1 Answers

Actually, I think that this sentence is a bit misleading. You can create a value of Arguments at runtime using format_args!. What you cannot do is to build an Arguments using an arbitary string format expression.

This is because the main invarants hold in Arguments are:

  1. Every placeholder has an argument.
  2. Every argument is used at least once.
  3. Every argument implements the proper trait that every argument implements the proper trait.

For example, if your string format is "{0}{1:?}{2:x}{2:X}" then you must have three arguments: the first one must implement Display, the second one Debug and the third one LowerHex + UpperHex.

You could create an API to build an Arguments in runtime with such invariants, but not by using a non-const format string. Because how would you know what traits to require? And what is the point of that? If you want to format your objects not using a string format, there is no reason to require an Arguments in the first place.

By requiring that the string is a literal, the macro format_args! can check during compile time that the arguments implement the proper traits.

Related