I am implementing a struct MyStruct with a method that should print something in the console. The ideia is the following: I can set a replacement string in MyStruct, for instance MyStruct::set("some", "other"), so that if I execute MyStruct::println("some"), then "other" should show in the console. The main problem is that Rust has no variadic functions. I could probably take a string array instead, but that brings some difficult to read syntax. Any crate or some Rust hidden magic feature that might help with this?
I don't see why you'd need varargs for that?
What's difficult about an array?
What you write there looks like MyStruct
is some kind of hash map or the like. Which Rust already has in its standard library.
I don't see how variadic functions are required for what you have written.
In Rust what looks like variadic functions is created with macros, like println!
for example.
something like the format! macro?
edit: oops, I didnt notice @Zicog already mentioned this in previous comment
I actually wanted something really close println! macro. So it would be possible to do somenthing like:
MyStruct::println("{} {} {:?}", "some", 1, [1, 2, 3]);
// Should print "other 1 [1, 2, 3]"
Do you want to have a function that accepts a Arguments in std::fmt - Rust ?
No quite. MyStruct should have the feature of replacing some arguments before printing:
MyStruct::set("foo", "bar");
MyStruct::println("{} {} {:?}", "foo", 1, [1, 2, 3]);
// Should print "bar 1 [1, 2, 3]"
Note that not foo
, but bar
was printed.
You could implement that, but your custom print needs to be a macro to support varargs. It may also not be obvious to the reader what is happening, so be considerate.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.