Prevent generating maybe_-prefixed method, and a way to provide the default value from within fn new
#203
Unanswered
teohhanhui
asked this question in
Q&A
Replies: 1 comment 12 replies
-
|
Hi! (1) Could you elaborate so I better understand the motivation? Why would you like to remove the (2) It's already possible to provide the default value from inside the function body use bon::bon;
struct TilePos {
x: u32,
y: u32,
}
#[bon]
impl TilePos {
#[builder]
fn new(x: u32, y: Option<u32>) -> Self {
Self {
x,
y: y.unwrap_or_else(|| x * 2),
}
}
}
fn main() {
// You can get the default value if you don't call `y/maybe_y` setters at all
let value = TilePos::builder().x(3).build();
assert_eq!(value.y, 6);
// ...or if you pass `None` to `maybe_y` setter
let value = TilePos::builder().x(3).maybe_y(None).build();
assert_eq!(value.y, 6);
}Alternatively, the same could be written with #[derive(bon::Builder)]
struct TilePos {
x: u32,
#[builder(default = x * 2)]
y: u32,
}
fn main() {
// You can get the default value if you don't call `y/maybe_y` setters at all
let value = TilePos::builder().x(3).build();
assert_eq!(value.y, 6);
// ...or if you pass `None` to `maybe_y` setter
let value = TilePos::builder().x(3).maybe_y(None).build();
assert_eq!(value.y, 6);
} |
Beta Was this translation helpful? Give feedback.
12 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I think there should be a way to prevent generating the
maybe_-prefixed method, i.e. only make the call optional with no way of explicitly settingNone.It'd be nice to have a way to provide the default value from inside the function body of
fn new, e.g.Beta Was this translation helpful? Give feedback.
All reactions