#Format
#Format() is the one attribute written before a parameter. It marks a char8[..] parameter as a format string, followed by a variadic parameter whose arguments fill its placeholders. When a call passes a string literal for it, the compiler counts the placeholders against the arguments and refuses a mismatch while compiling, rather than leaving it to fail at run time.
format-parameter = "#Format" "(" ")" identifier ":" "char8[..]"
The standard printing functions are declared this way:
pub func PrintLine(#Format() format: char8[..], args: Display...) -> IoError?
A function of your own takes it just as well; the compiler recognizes no package or function by name, only the attribute:
import Io::PrintLine;
import Format::Display;
func Log(level: int, #Format() format: char8[..], args: Display...) {
PrintLine(format, args...);
}
func Main() -> int {
Log(1, "{} of {}", 3, 4); // 3 of 4
Log(1, "{{}} {:x}", 255); // {} ff
return 0;
}
Placeholders
A placeholder is {} or {:spec}; {{ and }} are literal braces and count for nothing. A call whose literal has a different number of placeholders than arguments is an error:
error: format string has 2 placeholders, but 1 argument was provided
note: format parameter 'format' of 'Log' declared at 'Src/Main.rux':4:32
help: pass one argument for each '{}' placeholder
Only a literal can be counted. A format held in a variable, a spread argument such as args..., and a spec the formatter itself would reject are left to the formatter's check at run time.
Rules
| Mistake | Error |
|---|---|
| no variadic parameter after it | '#Format' parameter 'format' must be followed by a variadic parameter |
| on the variadic parameter itself | '#Format' cannot be applied to variadic parameter 'args' |
| on two parameters | '#Format' is already applied to parameter 'a' |
| on the receiver | '#Format' cannot be applied to the receiver 'self' |
| with an argument | '#Format' does not accept arguments |
| another name before a parameter | unknown parameter attribute '#Trim' |
A function has at most one format string, and the variadic parameter it counts against must be the last parameter.
See also
- Parameters — variadic parameters and spreads
- Attributes — the declaration attributes
- Learn: Format, Variadic