-
|
I have a design problem, where I have a field in a struct, that I want to generate using the value from another field, and currently that other field is optional. I can't refer to it directly in So, what I'm looking to do is something like: #[derive(Builder)]
#[builder(finish_fn(vis = "", name = "build_internal"))]
struct Blah {
#[builder(finish_fn)]
generated_async_using_x: bool,
#[builder(getter(copy))]
x: Option<bool>,
}
impl<S: blah_builder::State> BlahBuilder<S> {
pub async fn build(self) -> Blah
where
S: IsComplete,
{
let current_x = self.get_x();
self.build_internal(current_x.unwrap_or_default())
}
}However, this fails to compile, as My current workaround is to make the generated field optional, finish building first, and then mutably change the value; not ideal. #[derive(Builder)]
#[builder(finish_fn(vis = "", name = "build_internal"))]
struct Blah {
#[builder(skip)]
generated_async_using_x: Option<bool>,
#[builder]
x: Option<bool>,
}
impl<S: blah_builder::State> BlahBuilder<S> {
pub async fn build(self) -> Blah
where
S: IsComplete,
{
let mut built = self.build_internal();
built.x = Some(built.x.unwrap_or_default());
built
}
}So it works, but now I have to call |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Hi! If you have a complex async computation for an interdependent field, you might need to use a more flexible function-based syntax for the builder in this case. So it'll look like this: struct Blah {
generated_async_using_x: bool,
x: Option<bool>,
}
#[bon::bon]
impl Blah {
#[builder]
async fn new(x: Option<bool>) -> Self {
Self {
// can be any async/await expression here
generated_async_using_x: x.unwrap_or_default(),
x,
}
}
}
async fn example() {
let _blah = Blah::builder().x(true).build().await;
} |
Beta Was this translation helpful? Give feedback.
Hi! If you have a complex async computation for an interdependent field, you might need to use a more flexible function-based syntax for the builder in this case. So it'll look like this: