Modify both inner and outer part of a nested structure in a loop
13:46 26 Feb 2026

I'm trying to use a loop to build an arrow array of lists of structs, but have been stuck with mutable borrow issues:

let mut list_builder = ListBuilder::new(StructBuilder::from_fields(FieldsOfKeyAndValue, 0));
let struct_builder = list_builder.values();

let (field_builder_key, field_builder_value) = struct_builder.field_builders_mut().split_at_mut(1);
let key_builder = field_builder_key[0].as_any_mut().downcast_mut::().unwrap();
let value_builder = field_builder_value[0].as_any_mut().downcast_mut::().unwrap();

for (k, v) in Map {
    key_builder.append_value(k);
    value_builder.append_value(v);
    struct_builder.append(true); 
    list_builder.append(true); // Compiler complains list_builder have more than one mutable borrows
}
list_builder.finish()

In essence, I need to mutably access both the list_builder and struct_builder (which is acquired via list_builder.values()). I believe since they are in a loop, the compiler thinks list_builder cannot be mutably borrowed even after the last use of struct_builder in the same iteration.

I saw chained calls and temporary values being used elsewhere (e.g. https://github.com/apache/datafusion/blob/33b86fe02e7bbe63135995c2dbb47bf83c08143c/datafusion/core/tests/dataframe/mod.rs#L5211) that workarounds the borrow issue, however this would become very lengthy and unreadable for complex structures.

Is there a better way to avoid the multiple mut borrow issue?

rust apache-arrow