Crate named_tup

source ·
Expand description

githubcrates-iodocs-rs


This crate provides the tup! macro to produce named tuples, a struct that can contain a set of named arguments. Each named tuple can be added together or even default to a value if it does not already exist.

The idea of named tuples is to provide a way to quickly iterate on ideas without having to create a builder struct or losing the ability to type check at compile time. Named tuples also allow the creation of default values that can replace nonexistent arguments.

[dependencies]
named-tup = "0.3.1"

[build-dependencies]
inwelling = "0.4.0"

[package.metadata.inwelling.named-tup-derive]

And put the following in your build.rs file.

fn main() {
    inwelling::register();
}

If you would prefer for this crate to not scan your project files to determine what named arguments are being used add a list of the named tup arguments you used in your Cargo.toml like so.

[package.metadata.inwelling.named-tup-derive]
arguments = ["count", "ingredients", "eggs", "price"]

§Examples

use named_tup::tup;
let count = 5;

// This will have the type of Tup!(count: i32, ingredients: [&str; 3], eggs: bool)
let cakes = tup!(count, ingredients: ["milk", "flower", "sugar"], eggs: true);

// We can just add a price afterwards
let mut cakes = cakes + tup!(price: 3);
// And now it has the type of Tup!(eggs: bool, ingredients: [&str; 3], count: i32, price: i32)

// Once the price is in the tup we can just update it!
cakes.price = 4;

// Will print tup { count: 5, eggs: true, ingredients: ["milk", "flower", "sugar"], price: 4 }
println!("{cakes:?}");

To use defaults just annotate the item where you set a field with #[tup_default]. Additionally since the defaulted Tup! is a type you need to convert into it by calling .into_tup() which can be accessed through the TupInto trait.

use named_tup::{tup,Tup, tup_default, TupInto};

let options = tup!(read: false, write: true);

// Converts to Tup!(read: false, write: true, create: false, timeout: 5)
open_file("main.rs", options.into_tup());

#[tup_default]
fn open_file(
    path: &str,
    options: Tup!(
        read: bool = true,
        write: bool = false,
        create: bool = false,
        timeout: i32 = 5
    ))
{
    // Open the file
}

Macros§

  • Produces a type annotation for the tup struct. If an expression is needed instead please use the tup! macro.
  • The whole point.

Traits§

  • A copy of the From trait from the standard library. The From trait could unfortunately not be used due to it’s type reflexivity which clashed with the Tup implementation.
  • A copy of the Into trait from the standard library. The Into trait could unfortunately not be used due to it’s type reflexivity which clashed with the Tup implementation.

Attribute Macros§

  • An attribute macro that allows you to derive defaults.