3 ms·
Everything which needs the format-arbitrary-parameters feature in Rust is built out of macros, so yes it's the reason that println! is a macro. Even with no_std
by tialaramex 4y ago
Everything which needs the format-arbitrary-parameters feature in Rust is built out of macros, so yes it's the reason that println! is a macro. Even with no_std where you don't have an Allocator, and so you can't use format! to get Strings (because there aren't any Strings) you still have mechanisms built out of macros, so you could e.g. write six u16s and a f32 to the serial port on your embedded controller (you could write a &str, but since you can't allocate Strings it'll have to be some pre-defined value like "Error" or "OK").
These functions are especially tricky because we want to have a variable number of arguments with arbitrary types. We want to be able to print two bytes, a string, an array, and six different arbitrary data structures we decided were important.
There are lots more applications for function(a, b, c, d, ...) where a, b, c and so on are all the same type. It might be nice to define min() and max() over these parameters for example. But cases like print-format where it's sane to choose unrelated types are rarer. Languages where I can write min("Cheese", 4, tmpfile, -Inf) have lots of other problems that outweigh the potential usefulness of such constructions.
I expect that if somebody can write a sound but ergonomic varargs story for safe Rust it'll get introduced, even if they can't solve print-format it's still useful as I showed above.
- the_duke 4y agoVarargs with the same type is just a list. In many languages that could require an extra allocation, but in Rust that can just be a slice or maybe a an array with a const generic for it's size if you want to pass ownership. Varargs here would really just be a minor ergonomics improvement. Heterogeneous varargs would be more useful, but would require something like variadic generics. (which have been proposed before)