TakeField
Removing one currently-present field from a builder.
Overview
Context-Generic Programming (CGP) assembles and takes apart structs generically, by their
field names. TakeField is the reverse of BuildField: it removes a field that
is currently set, handing back the value and the
partial record without it. The value comes out owned, and
the remainder is the partial record with that one field flipped back to absent, so it can no longer
be finalized until the field is put back.
It pins the IsPresent → IsNothing transition of the UpdateField primitive, and
because it requires the starting marker to be IsPresent, taking a field that is absent is a compile
error rather than an Option you have to handle.
Two uses reach for it. One is redistributing a record: into_builder, take fields
out, put them somewhere else. The other, far more often, is CanBuildFrom,
whose merge recursion takes each field out of the source and builds it into the target.
Definition
TakeField is keyed by the field's Tag, with two associated types and one method:
pub trait TakeField<Tag> {
type Value;
type Remainder;
fn take_field(self, _tag: PhantomData<Tag>) -> (Self::Value, Self::Remainder);
}
Tag names the field. Value is the field's declared type, returned owned. Remainder is the partial
record with that one field's marker flipped from IsPresent back to IsNothing, a different type from
Self that can no longer be finalized until the field is restored. take_field returns the two as a
tuple, the value first and the remainder second. The blanket impl over UpdateField
that supplies this is shown in Under the hood.
Usage
It is not in the prelude, like the rest of the core builder family. Import it from
cgp::core::field::traits when you call take_field directly:
use cgp::core::field::traits::TakeField;
The PhantomData<Tag> argument names the field, and the method returns a tuple: the value first, the
remainder second.
Nothing implements it directly. It is a library blanket impl over
UpdateField, so every field the derive generates an UpdateField impl for
gains take_field without an impl of its own.
Examples
Taking a field out of a full builder, changing it, and putting it back:
use cgp::core::field::traits::{BuildField, FinalizeBuild, IntoBuilder, TakeField};
use cgp::prelude::*;
#[derive(Debug, PartialEq, BuildField)]
pub struct Person {
pub first_name: String,
pub last_name: String,
}
pub fn shout_first_name(person: Person) -> Person {
let (first_name, remainder) = person
.into_builder()
.take_field(PhantomData::<Symbol!("first_name")>);
remainder
.build_field(
PhantomData::<Symbol!("first_name")>,
first_name.to_uppercase(),
)
.finalize_build()
}
pub fn demo() {
let person = Person {
first_name: "Alice".to_owned(),
last_name: "Chen".to_owned(),
};
assert_eq!(shout_first_name(person).first_name, "ALICE");
}
Dropping the build_field step makes finalize_build fail to resolve, which is the guarantee: a
field taken out and not replaced cannot be forgotten silently.
When to use it
Reach for it when a complete value must be decomposed, and remember that the common case, merging one record into another, already uses it for you.
- Use
CanBuildFromto move every field of one record into another's builder. It is this trait applied in a loop, written once. - Use
take_fieldwhen a specific field must be extracted from a partial value, typically afterinto_builder. - Use
BuildFieldfor the opposite direction. - Use
ToFieldswhen the whole value should become a flat shape rather than a partial record with one field missing. - Prefer ordinary destructuring in concrete code.
let Person { first_name, .. } = person;needs none of this machinery, and this family is for code that cannot name the type.
Under the hood
TakeField is a library blanket impl over UpdateField, the mirror image of
BuildField:
impl<Context, Tag> TakeField<Tag> for Context
where
Context: UpdateField<Tag, IsNothing, Mapper = IsPresent>,
{
type Value = Context::Value;
type Remainder = Context::Output;
fn take_field(self, tag: PhantomData<Tag>) -> (Self::Value, Self::Remainder) {
self.update_field(tag, ())
}
}
The target marker is IsNothing and the constraint on the reported source marker is IsPresent,
both swapped relative to BuildField, so under this transition the primitive takes () in and
hands the real value back. Its heaviest user is CanBuildFrom,
whose recursion walks the source's field list, taking each field out with take_field and writing
it into the target with build_field, which is why a merge needs
HasFields on the source as well as a builder.
Common Mistakes
It is not in the prelude. Import from cgp::core::field::traits. The rest of the core builder
family comes from there too.
Taking an absent field does not compile. Taking first_name from an empty builder:
let _ = Person::builder().take_field(PhantomData::<Symbol!("first_name")>);
finds Mapper = IsNothing where the blanket impl requires IsPresent, reported as a mismatch
rather than as anything about absence:
error[E0271]: type mismatch resolving `<__PartialPerson<IsNothing, IsNothing> as UpdateField<Symbol<10, Chars<'f', Chars<'i', Chars<'r', Chars<'s', Chars<'t', Chars<'_', Chars<'n', Chars<'a', Chars<'m', Chars<'e', Nil>>>>>>>>>>>, IsNothing>>::Mapper == IsPresent`
...
note: expected this to be `IsPresent`
It returns (value, remainder), in that order. Reversing the binding is a type error, but a
confusing one when both are generic.
The remainder cannot be finalized. That is the point, and it means a decomposition that loses a field
fails at finalize_build rather than where the field was dropped.
Remainder is a different type from Self, so a take cannot happen in a loop over a fixed-type
variable.
Nothing implements it directly, so an unsatisfied TakeField bound surfaces as an unsatisfied
UpdateField one.
Related constructs
BuildField: the opposite direction.UpdateField: the primitive both are built from.IntoBuilder: how a complete value becomes a partial one to take from.CanBuildFrom: the merge that uses this internally.FinalizeBuild: what a remainder cannot satisfy until the field is restored.HasBuilder: the family's entry point.MapType: theIsPresent/IsNothingmarkers this moves between.ToFields: the flat-shape alternative to decomposing a partial value.#[derive(BuildField)]: generates theUpdateFieldimpls behind it.
The ideas behind it:
- Extensible records: partial records and the extensible builder pattern.
Source
take_field.rs:TakeField
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.