Skip to main content

ToFields

Taking a value apart into its shape.

Overview​

In Context-Generic Programming (CGP), HasFields names a type's shape. ToFields produces a value in it.

That lets generic code stop working on a concrete struct and start working on an anonymous list of named entries: the form a serializer walks, a converter rewrites, or a merge consumes. The concrete type goes in; a Product! of Field entries comes out, or a Sum! for an enum.

It consumes the value. That is the difference from ToFieldsRef, and it is the commonest surprise in the family, because the two read alike at a call site.

The reverse direction is FromFields, and the two round-trip through the identical Fields type, so generic code can decompose, transform, and rebuild with the shapes lining up by construction rather than by check.

Definition​

ToFields adds one method to the shape trait it extends:

pub trait ToFields: HasFields {
fn to_fields(self) -> Self::Fields;
}

It supertraits HasFields, so to_fields returns that trait's Fields shape and a bound on ToFields gives you Fields as well. The method takes self by value, so it consumes the value to produce the owned shape.

Usage​

It is not in the prelude. Import it from cgp::core::field::traits. Writing T: HasFields + ToFields is common and harmless, though T: ToFields alone already gives you Fields through the supertrait.

The impls come from #[derive(HasFields)], which emits all five shape traits together.

Examples​

A value taken apart by a generic function, read from the product, and rebuilt:

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,
}

pub fn shape_of<T>(value: T) -> T::Fields
where
T: ToFields,
{
value.to_fields()
}

pub fn demo() {
let config = Config {
host: "localhost".to_owned(),
port: 8080,
};

let fields = shape_of(config.clone());
assert_eq!(fields.1 .0.value, 8080);

assert_eq!(Config::from_fields(fields), config);
}

fields.1.0 is the second entry of the Cons chain, the port field, and from_fields puts the value back together. The clone() is there only because the assertion compares against the original, which to_fields consumes.

When to use it​

Bound on it when generic code must consume a value and work on its entries, and reach for the borrowing form otherwise.

  • ToFieldsRef when the value must survive. Requiring ToFields where a borrow would do forces every caller to clone, which is the most common over-requirement in this family.
  • FromFields for the other direction, and both together for a round trip.
  • HasFields alone when the code only names the shape and never holds a value in it.
  • HasField when one named field is all that is wanted. Decomposing a whole struct to read one entry is the wrong tool.
  • The builder family when a value is assembled incrementally rather than converted wholesale. to_fields is a single flat conversion; a builder tracks presence field by field.

Under the hood​

Product![A, B] is Cons<A, Cons<B, Nil>>, so the conversion builds a Cons chain, one node per field, converting each value into its Field entry with into. cargo cgp expand on the example's Config shows:

impl ToFields for Config {
fn to_fields(self) -> <Self as HasFields>::Fields {
Cons(self.host.into(), Cons(self.port.into(), Nil))
}
}

An error message prints that chain when structural code fails to resolve, and the type-level lists page covers reading it.

An enum's conversion is the dual: each variant is matched onto its arm of the Either chain, as Self::Square(field) => Either::Right(Either::Left(field.into())) for the second variant of an enum.

Because the shape is built positionally from declaration order, to_fields and from_fields are exact inverses by construction: there is no lookup, no matching by name at run time, and nothing that can fail.

Common Mistakes​

It consumes the value. Reach for ToFieldsRef when you need to keep it. This is the commonest surprise in the family, because the two read alike.

Field order is declaration order and is part of the type. Two structs with the same field names in different orders produce unrelated Fields types, so a chain built from one will not satisfy the other.

A newtype's shape is the inner type, not a one-element product, so to_fields on struct Wrapper(String) yields a String. Generic code written against a Cons chain will not match it.

It supertraits HasFields, so a bound naming both is redundant rather than wrong.

There is no fallible form. The conversion cannot fail; anything that could is a different operation, such as a cast.

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.