FromFields
Rebuilding a concrete value from its shape.
Overview
In Context-Generic Programming (CGP), ToFields takes a value apart
into an anonymous list of named entries. FromFields is the return journey. It closes the loop for generic code: decompose a value, work on
the entries without naming the type, and put a concrete value back together at the end. Both
directions go through the identical Fields type, so the shapes line up by construction rather
than by check: there is nothing to validate and nothing that can fail.
Definition
FromFields adds one associated function to the shape trait it extends:
pub trait FromFields: HasFields {
fn from_fields(fields: Self::Fields) -> Self;
}
It supertraits HasFields, so
from_fields takes that trait's Fields shape and a bound on FromFields gives you Fields as
well. It is an associated function rather than a method, because there is no value to call it on, so
the call reads Person::from_fields(fields), or T::from_fields(fields) in generic code.
Usage
It is not in the prelude. Import it from cgp::core::field::traits. The impls come from
#[derive(HasFields)], which emits all five shape traits
together.
The argument must be exactly Self::Fields: the same entries, the same tags, in the same order.
A shape that merely has the same field names in a different order is a different type and will not
be accepted, which makes the conversion total.
Examples
A generic round trip through the shape, for a struct and an enum:
use cgp::core::field::traits::{FromFields, ToFields};
use cgp::prelude::*;
#[derive(Clone, Debug, Eq, PartialEq, HasFields)]
pub struct Config {
pub host: String,
pub port: u16,
}
#[derive(Clone, Debug, PartialEq, HasFields)]
pub enum Shape {
Circle(f64),
Square(f64),
}
pub fn round_trip<T>(value: T) -> T
where
T: ToFields + FromFields,
{
T::from_fields(value.to_fields())
}
pub fn demo() {
let config = Config {
host: "localhost".to_owned(),
port: 8080,
};
assert_eq!(round_trip(config.clone()), config);
assert_eq!(round_trip(Shape::Square(2.0)), Shape::Square(2.0));
}
An enum rebuilds from a Sum! rather than a product: the arm that is present
becomes the variant that is constructed.
When to use it
Bound on it when generic code produces a concrete value from entries it has assembled or
transformed. Pair it with ToFields for a round trip, and require only one of
the two when only one direction happens.
ToFieldsfor the decomposition half.HasFieldsalone when the code names the shape and never builds a value.- The builder family when the value is assembled incrementally,
from pieces arriving at different times.
from_fieldsneeds the whole shape at once, already complete;HasBuildertracks presence field by field, and the extensible builder pattern uses it. FromVariantwhen an enum is built from one named variant rather than from a whole shape. That is the far more common way to construct an enum generically.- A plain constructor when the type is concrete. Nothing about
from_fieldsimproves on a struct literal where one can be written.
Under the hood
The conversion destructures the Cons chain positionally and unwraps each entry's value.
cargo cgp expand on the example's Config shows:
impl FromFields for Config {
fn from_fields(Cons(host, Cons(port, Nil)): <Self as HasFields>::Fields) -> Self {
Self {
host: host.value,
port: port.value,
}
}
}
The shape is matched apart in the signature itself, one node per field, terminated by Nil. Because
the chain is built and matched in declaration order, this is the exact inverse of
to_fields: nothing is looked up by name at run time, and the tags exist only to
make the types distinct. An enum's impl is the dual, a match down the Either chain, and the
example's Shape ends in an empty match on the Void terminator:
impl FromFields for Shape {
fn from_fields(rest: <Self as HasFields>::Fields) -> Self {
match rest {
Either::Left(field) => {
let field = field.value;
Self::Circle(field)
}
Either::Right(rest) => {
match rest {
Either::Left(field) => {
let field = field.value;
Self::Square(field)
}
Either::Right(rest) => match rest {}
}
}
}
}
}
Common Mistakes
It is an associated function, not a method. Write T::from_fields(fields); there is no
receiver.
The shape must match exactly. Same tags, same value types, same order. Two structs with
identical field names in different orders have unrelated Fields types, and the mismatch is
reported against the whole chain rather than against the field that moved.
A newtype's shape is the inner type, not a one-element product, so from_fields on
struct Wrapper(String) takes a String.
It supertraits HasFields, so naming both in a bound is redundant.
It cannot build a value incrementally. The whole shape is required at once. Assembling from
independent pieces is HasBuilder's job, and reaching for
from_fields there means constructing the complete product by hand first.
There is no borrowing counterpart. ToFieldsRef has no FromFieldsRef,
because a borrowed shape cannot yield an owned value.
Related constructs
ToFields: the reverse conversion, and the one usually written first.HasFields: the supertrait that names the shape.ToFieldsRefandHasFieldsRef: the borrowed half of the family, which has no rebuild.FromVariant: constructing an enum from one named variant.HasBuilder: incremental assembly, as against this wholesale conversion.#[derive(HasFields)]: generates this impl.Product!,Sum!, andField: what a shape is made of.
The ideas behind it:
- Extensible records: a struct as a product of named fields.
- Extensible variants: the enum half.
Source
from_fields.rs:FromFields
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.