In many languages, a common constructor idiom is to initialize values of an object using syntax like this pseudocode:
constructor Foo(args...) {
for arg {
object.arg = arg
}
}
Rust at first seems to be no exception. Many impl for a struct include a constructor named new to zip an ordered series of arguments onto the fields of the struct:
struct Circle {
x: i32,
y: i32,
radius: i32,
}
impl Circle {
fn new(x: i32, y: i32, radius: i32) -> Circle {
Circle { x: x, y: y, radius: radius }
}
}
Doing this with a macro might look like zip!(Circle, 52, 32, 5). It would zip the values, in order, onto the fields of Circle. Both zip!(Circle, 52, 32) or zip!(Circle, 52, 32, 5, 100) would present issues, but a macro like this would be a very flexible way to push values onto a new instance of any struct without so much boilerplate.
Is there an idiomatic way to simplify this boilerplate? How is it possible to map a series of ordered arguments onto each field of a struct without explicitly writing the boilerplate code to do so?