proc-macro for accessing struct field names at runtime

Overview

field_names

Build Status Latest Version

field_names is a Rust crate to expose a field or variant names from source code as strings at runtime.

Example

Consider a simple struct such as this one.

#[derive(FieldNames)]
struct Example {
    hello: String,
    world: String,
    #[field_names(skip)]
    ignore_me: bool,
}

field_names will emit the following:

#[automatically_derived]
impl Example {
    const FIELDS: [&'static str; 2] = [
        "hello",
        "world",
    ];
}

Enums are the same:

#[derive(VariantNames)]
enum Example {
    Hello(String),
    #[variant_names(skip)]
    Secret(String),
    World,
}

field_names will emit the following:

#[automatically_derived]
impl Example {
    const VARIANTS: [&'static str; 2] = [
        "Hello",
        "World",
    ];
}

Uses

This crate was originally created for a case where a set of rules were being read at runtime which referenced fields of structs elsewhere in the code base. The referenced struct exposed a method which had a match statement to go from strings to its fields, but there was not a way to ensure the arms of that match statement stayed in sync with the struct definition. With this crate, a unit test could be created to ensure that every field on the struct - except those deliberately omitted - was handled by the method.

This crate can also be used to enforce relationships among structs and enums at unit-test time that cannot be expressed at compile-time. See tests/keep_in_sync for an example and explanation of that scenario.

FAQs

Why aren't FieldNames and VariantNames traits?

Using field_names is an implementation convenience; it shouldn't force you to change your crate's public API.

How do I make FIELDS or VARIANTS public?

You can add your own inherent method, e.g. fields() -> &[&'static str], or define a trait that matches your use-case and reference FIELDS in the trait implementation.

Can I get field names for an enum variant?

This currently isn't supported, using newtype variants and separate structs per variant is currently the recommended approach. You can use the from_variants crate to auto-generate conversions from those structs into the enum.

You might also like...
An LR parser generator, implemented as a proc macro

parsegen parsegen is an LR parser generator, similar to happy, ocamlyacc, and lalrpop. It currently generates canonical LR(1) parsers, but LALR(1) and

A fully-featured lexer generator, implement as a proc macro

lexgen: A fully-featured lexer generator, implemented as a proc macro lexer! { // First line specifies name of the lexer and the token type return

Example of structuring a proc macro crate for testability

testing-proc-macros Example of structuring a proc macro crate for testability. See accompanying blog post for details. License Licensed under either o

A Rust proc-macro crate which derives functions to compile and parse back enums and structs to and from a bytecode representation

Bytecode A simple way to derive bytecode for you Enums and Structs. What is this This is a crate that provides a proc macro which will derive bytecode

Example of using nom parsers from a proc macro

Example of using nom parsers from a proc macro This project is organised as 3 crates: nom_macro is the main project, exposing the proc macro and the g

Macros to make writing proc-macro crates easy

proc-easy Macros to make writing proc-macro crates easy. This crate provides mainly macros and supporting types and traits to reduce amount of boilerp

Proc macro implementation of #[naked]

#[naked] Documentation This crate provide a proc macro version of the #[naked] attribute which can be used on stable Rust. Example // The SYSV64 calli

A rust proc-macro which allows for reading and writing to remote objects through a generated enum

Remote-Obj A rust proc-macro which allows for reading and writing fields/variants of (possibly nested) remote objects by generating a single enum whic

A proc macro for creating compile-time checked CSS class sets, in the style of classNames

semester Semester is a declarative CSS conditional class name joiner, in the style of React's classnames. It's intended for use in web frameworks (lik

Library and proc macro to analyze memory usage of data structures in rust.
Library and proc macro to analyze memory usage of data structures in rust.

Allocative: memory profiler for Rust This crate implements a lightweight memory profiler which allows object traversal and memory size introspection.

Proc. macro to generate C-like `enum` tags.

Continuous Integration Documentation Crates.io #[derive(EnumTag)] This crate provides a proc. macro to derive the EnumTag trait for the given Rust enu

ChatGPT powered Rust proc macro that generates code at compile-time.

gpt-macro ChatGPT powered Rust proc macro that generates code at compile-time. Implemented Macros auto_impl!{} #[auto_test(...)] Usage Get ChatGPT API

proc-macro to help with using surrealdb's custom functions

SurrealDB Functions This is a proc-macro crate that given a path to a .surql file or a folder of .surql files, will parse DEFINE FUNCTION fn::s inside

Rust bindings for accessing the Go containers/image stack

Rust bindings for accessing the Go containers/image stack This crate contains a Rust API that forks /usr/bin/skopeo and talks to it via a custom API.

Rust bindings for accessing the Go containers/image stack

Rust bindings for accessing the Go containers/image stack This crate contains a Rust API that forks /usr/bin/skopeo and talks to it via a custom API.

🐱‍👤 Cross-language static library for accessing the Lua state in Garry's Mod server plugins

gmserverplugin This is a utility library for making Server Plugins that access the Lua state in Garry's Mod. Currently, accessing the Lua state from a

Dufs is a distinctive utility file server that supports static serving, uploading, searching, accessing control, webdav...
Dufs is a distinctive utility file server that supports static serving, uploading, searching, accessing control, webdav...

Dufs (Old Name: Duf) Dufs is a distinctive utility file server that supports static serving, uploading, searching, accessing control, webdav... Featur

A file server that supports static serving, uploading, searching, accessing control, webdav...
A file server that supports static serving, uploading, searching, accessing control, webdav...

Dufs Dufs is a distinctive utility file server that supports static serving, uploading, searching, accessing control, webdav... Features Serve static

The [cain!] macro is a macro that rewrites sequential Rust branch statements into nested branches

Note! This crate is experimental and under development. It may include bugs that alter the behavior of your code in unexpected ways. You should review

Comments
  • Feature Request: Derive Enum types

    Feature Request: Derive Enum types

    It would be useful if you could also have a similar derive for getting the enum types.

    Currently, when parsing a string to match an enum my error messages are handwritten. Could be dynamically generated.

    enhancement 
    opened by cgbur 3
Releases(v0.2.0)
Owner
Ted Driggs
ExtraHop Product Manager & API Designer, Rust dev, skier, horseback rider, and stand-up paddleboarder
Ted Driggs
Autodefault automatically makes your struct literals fill themselves with `..default()`

autodefault A library that automatically inserts ..Default::default() for you. The pitch Has this ever happened to you? #[derive(Debug, Default, Parti

Nathan West 59 Dec 7, 2022
Statically verified Rust struct field names as strings.

field Statically verified struct field names as strings. See the documentation for more details. Installation Add the following to your Cargo manifest

Indraneel Mahendrakumar 3 Jul 9, 2023
A proc-macro to get Vec from struct and vise versa

byteme A proc-macro to convert a struct into Vec and back by implemeting From trait on the struct. The conversion is Big Endian by default. We have ma

Breu Inc. 11 Nov 4, 2022
Number names is a Rust library to provide formatted string names for cardinal and ordinal numbers.

Number Names Number names is a Rust library to provide formatted string names for cardinal and ordinal numbers. At this time, only American English is

Calteran 12 Dec 5, 2022
Easy c̵̰͠r̵̛̠ö̴̪s̶̩̒s̵̭̀-t̶̲͝h̶̯̚r̵̺͐e̷̖̽ḁ̴̍d̶̖̔ ȓ̵͙ė̶͎ḟ̴͙e̸̖͛r̶̖͗ë̶̱́ṉ̵̒ĉ̷̥e̷͚̍ s̷̹͌h̷̲̉a̵̭͋r̷̫̊ḭ̵̊n̷̬͂g̵̦̃ f̶̻̊ơ̵̜ṟ̸̈́ R̵̞̋ù̵̺s̷̖̅ţ̸͗!̸̼͋

Rust S̵̓i̸̓n̵̉ I̴n̴f̶e̸r̵n̷a̴l mutability! Howdy, friendly Rust developer! Ever had a value get m̵̯̅ð̶͊v̴̮̾ê̴̼͘d away right under your nose just when

null 294 Dec 23, 2022
Easy access of struct fields in strings using different/custom pre/postfix: "Hello, {field}" in rust

Easy access to struct fields in strings ?? add strung to the dependencies in the Cargo.toml: [dependencies] strung = "0.1.3" ?? use/import everything

Dekirisu 2 Sep 19, 2022
Derive with constructor for each field in struct.

A custom derive implementation for #[derive(with)] Get started 1.Generate with constructor for each field use derive_with::with; #[derive(with, Defau

SystemX Labs 4 Oct 22, 2023
Simple rust asset handling derive macro for enums, and a proc-macro learning resource!

asset-derive Summary • Todos • Docs Summary Simple Rust asset loading derive macro for Enums, and a resource for learning proc-macros! Please feel fre

Shadorain 5 Feb 9, 2023
This crate allows writing a struct in Rust and have it derive a struct of arrays layed out in memory according to the arrow format.

Arrow2-derive - derive for Arrow2 This crate allows writing a struct in Rust and have it derive a struct of arrays layed out in memory according to th

Jorge Leitao 29 Dec 27, 2022
A procedural macro to generate a new function implementation for your struct.

Impl New ?? A procedural macro to generate a new function implementation for your struct. ?? Add to your project Add this to your Cargo.toml: [depende

Mohammed Alotaibi 4 Sep 8, 2023