Skip to main content

SetOptional

Setting one field of an optional builder, as many times as you like.

Overview​

When Context-Generic Programming (CGP) assembles a struct generically, BuildField sets an absent field and consumes the slot: the builder's type changes, and setting the same field twice is a compile error. SetOptional is the optional layer's answer, and its defining property is the opposite: an optional field is settable in any order and as many times as you like.

Definition​

SetOptional<Tag> is keyed by the field's tag and exposes the field's type as an associated Value:

pub trait SetOptional<Tag> {
type Value;

fn set(self, _tag: PhantomData<Tag>, value: Self::Value) -> Self;

fn set_optional(
self,
_tag: PhantomData<Tag>,
value: Self::Value,
) -> (Option<Self::Value>, Self);
}

Tag is the field's type-level name, a Symbol! for a named field or an Index<N> for a tuple field, passed at the call site as a PhantomData<Tag> argument. Value is the field's declared type, so a caller passes an ordinary value rather than an Option. Both methods take self and return Self: the field's marker stays IsOptional before and after, so the builder's type does not change and an optional field can be set repeatedly. The two methods differ only in what they do with whatever was already there. set discards it; set_optional returns it as an Option<Self::Value> alongside the rebuilt builder. The trait does not declare a supertrait. It is not in the prelude; import it from cgp-field-extra.

Usage​

It is not in the prelude. Import it from cgp::extra::field::impls:

use cgp::extra::field::impls::SetOptional;

Self must be an optional builder, one from optional_builder() or to_optional(). Calling it on a core builder does not resolve, because the field's marker is IsNothing rather than IsOptional. The trait lacks an "unset" operation: a field starts absent and stays so unless it is set.

Examples​

Setting fields in any order, and re-setting one:

use cgp::prelude::*;
use cgp::extra::field::impls::{FinalizeOptional, HasOptionalBuilder, SetOptional};

#[derive(Debug, PartialEq, CgpData)]
pub struct Context {
pub foo: String,
pub bar: u64,
}

pub fn demo() {
let builder = Context::optional_builder()
.set(PhantomData::<Symbol!("bar")>, 42)
.set(PhantomData::<Symbol!("foo")>, "foo".to_owned());

// Setting an already-set field hands back what it replaced.
let (replaced, builder) =
builder.set_optional(PhantomData::<Symbol!("foo")>, "bar".to_owned());
assert_eq!(replaced, Some("foo".to_owned()));

let context = builder.finalize_optional().unwrap();
assert_eq!(context.foo, "bar");
}

Because set returns Self, the calls chain exactly as core build_field calls do. The difference is invisible at the call site and lives entirely in the type.

When to use it​

Reach for it when a field may be set more than once, or when the order is not known. That is the one thing the core builder cannot express.

  • BuildField when each field is set exactly once. The compile-time completeness check it buys is the reason the core family exists.
  • set when whatever was there should be replaced.
  • set_optional when the previous value matters: merging, accumulating, or warning on a duplicate.
  • CanBuildFrom when the values come from another record wholesale rather than one at a time.

Under the hood​

SetOptional is a blanket impl over a single UpdateField call that writes Some(value) into an IsOptional slot, with both the source and target markers pinned to IsOptional:

impl<Context, Tag> SetOptional<Tag> for Context
where
Context: UpdateField<Tag, IsOptional, Mapper = IsOptional, Output = Context>,
{
type Value = Context::Value;

fn set(self, tag: PhantomData<Tag>, value: Self::Value) -> Self {
self.set_optional(tag, value).1
}

fn set_optional(
self,
tag: PhantomData<Tag>,
value: Self::Value,
) -> (Option<Self::Value>, Self) {
self.update_field(tag, Some(value))
}
}

Mapper = IsOptional requires the field to already be in the optional state, and Output = Context pins the result to the same type on both sides. That pinning allows repeated sets: the call does not consume a marker, so every impl that applied before it still applies after it.

Contrast BuildField, which pins Mapper = IsNothing and a target of IsPresent: its Output is a different type, which makes a second call fail to resolve.

Since the primitive returns the old storage alongside the new value, set_optional exposes it and set discards it. Under IsOptional that old storage is an Option<Value>, which is why the returned value is optional even though the argument is not.

Common Mistakes​

It is not in the prelude. Import from cgp::extra::field::impls.

It does not apply to a core builder. Calling set on a builder from builder():

let _ = Context::builder().set(PhantomData::<Symbol!("foo")>, "foo".to_owned());

fails both pins of the blanket impl, each reported as a mismatch:

error[E0271]: type mismatch resolving `<__PartialContext<IsNothing, IsNothing> as UpdateField<Symbol<3, Chars<'f', Chars<'o', Chars<'o', Nil>>>>, IsOptional>>::Mapper == IsOptional`
...
error[E0271]: type mismatch resolving `<__PartialContext<IsNothing, IsNothing> as UpdateField<Symbol<3, Chars<'f', Chars<'o', Chars<'o', Nil>>>>, IsOptional>>::Output == __PartialContext<IsNothing, IsNothing>`

The field must already be IsOptional, so start with optional_builder() or convert with to_optional().

The builder's type never changes, so it does not record what you have set. That is deliberate: it allows re-setting, and it is why finalizing has to check at run time.

set_optional returns (previous, builder), in that order. Reversing the binding is a type error, and a confusing one in generic code.

The argument is a Value, not an Option<Value>. The trait lacks an "unset" operation; a field left alone stays absent.

A field whose type is already Option<T> takes an Option<T> here and is stored as Option<Option<T>>. The outer layer is the builder's presence tracking, and the two are easy to conflate.

The ideas behind it:

Source​


An AI agent wrote this page using the CGP knowledge base. Its content was verified against the library's source. See How AI is used in this project.