Repository navigation
Replies: 1 comment
|
The simplest pattern is to keep each mutable borrow shorter than the next builder operation. A small helper makes that explicit and avoids repeating the chained calls: fn append_entry(builder: &mut StructBuilder, key: &str, value: &str) {
{
let (key_fields, value_fields) =
builder.field_builders_mut().split_at_mut(1);
key_fields[0]
.as_any_mut()
.downcast_mut::<StringBuilder>()
.unwrap()
.append_value(key);
value_fields[0]
.as_any_mut()
.downcast_mut::<StringBuilder>()
.unwrap()
.append_value(value);
} // the child-builder borrows end here
builder.append(true);
}
let mut list_builder =
ListBuilder::new(StructBuilder::from_fields(fields_of_key_and_value, 0));
for map in maps {
for (key, value) in map {
append_entry(list_builder.values(), key, value);
}
// One list slot per map / outer row, not one per key-value struct.
list_builder.append(true);
}
let array = list_builder.finish();There are two separate borrow conflicts in the original code:
The helper handles both: Also, each struct row must append exactly one value (or null) to every child builder before |
0 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'm trying to use a loop to build an array of lists of structs, but have been stuck with mutable borrow issues:
I have seen chained calls being used elsewhere (e.g. https://github.com/apache/datafusion/blob/33b86fe02e7bbe63135995c2dbb47bf83c08143c/datafusion/core/tests/dataframe/mod.rs#L5211), however this would become very lengthy and unreadable for complex structures, like the one in https://docs.rs/arrow/latest/arrow/array/struct.StructBuilder.html . Is there a better way to avoid the multiple mut borrow issue?
All reactions