Re:Rust Language Cheat Sheet
by unrealhoang on Sunday April 25, 2021 @09:07AM
(#26932398)
it's a hard design problem, actually.
But I think with const generic, we are getting very close, variadic could be:
[ Parent
| on HN ]
If I'm reading your intent right that would monomorphize to a slice of a specific N, meaning you couldn't express format!("{}{}", 1, 1.0)
I think you're reading the comment you replied to right, but I don't (completely) agree with your conclusion.
There are two magic things the format macro does apart from varargs, it checks the format string against the length and format types of the argument at compile time, and it automatically borrows the arguments. Implementing format with varargs means you need to lose those.
Once you lose those calling it looks like
format("{}{}", &1, &1.0)
under the above proposal the type signature of format would look like fn format<const N: usize>(fmt_str: &str, args: [&dyn Format; N]) -> Result<String, Error>;
Where `Format` replaces the various `Display`, `Debug`, etc traits and looks something like this trait Format {
fn display(&self, fmt: &mut Formatter) -> Result<(), Error> {
// Default implementation of this method
return Err(Error::NotImplemented)
}
fn debug(&self, fmt: &mut Formatter) -> Result<(), Error> {
// Default implementation of this method
return Err(Error::NotImplemented)
}
...
}
I.e. the trick is that the conversion to a trait object happens (implicitly) on the calling side when you take a reference, so all the arguments are all of the same type.