Skip to content

Support a .with_optional_field(name, value) method on StructBuilder #1015

@sadderchris

Description

@sadderchris

It's a little painful to add an optional field (one that may or may not be present in the final ion object) to an ion struct today. The ion_struct! { ... } macro assumes that you want each field you specify to be present in the output (it simply delegates to .with_field(...)). This makes it unusable for this purpose, so you have to fall back to the StructBuilder. Regardless, the StructBuilder only exposes a with_field method, which always adds the (name, value) pair to the final ion struct. Combined with the fact that the builder requires you to pass around ownership, this means you end up writing lots of code like

let builder = Element::struct_builder();

let builder = if let Some(my_value) = value {
    builder.with_field("my_field", my_value)
} else {
    builder
}

let builder = builder.with_field("quux", quux);

// ...

builder.build()

rather than being able to chain methods

Element::struct_builder()
    .with_field("foo", foo)
    .with_field("bar", bar)
    .build()

Adding a fn with_optional_field(self, name: impl Into<Symbol>, value: Option<impl Into<Element>>) -> Self method that only adds the (name, value) pair to the struct if the value is Some(...) would allow method chaining in this case and be a lot more ergonomic.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions