Macro tuplez::get

source ·
get!() { /* proc-macro */ }
Expand description

Get the element at a specific index of the tuple.

The get_ref() and get_mut() provide another way to get elements by their type.

§Syntax

get!(Expr; Index)

The index must be an integer literal since procedural macros do not yet support evaluating constants.

§Explanation

This macro will be expanded to standard member access syntax:

get!(tup; 0) => tup.0
get!(tup; 1) => tup.1.0
get!(tup; 2) => tup.1.1.0

Expressions are automatically quoted, so don’t worry:

get!(tup1 + tup2; 3) => (tup1 + tup2).1.1.1.0

You can use & and &mut directly on the output of get!, like:

use tuplez::{get, tuple};

fn add(x: &i32, y: &i32) -> i32 { x + y }

fn add_one(x: &mut i32) { *x += 1; }

let mut tup = tuple!(1, "hello", 3.14);

let x = add(&get!(tup; 0), &2);             // Immutably reference the first element of `tup`
assert_eq!(tup, tuple!(1, "hello", 3.14));  // Then `tup` remains unchanged
assert_eq!(x, 3);

add_one(&mut get!(tup; 0));                 // Mutably reference the first element of `tup`
assert_eq!(tup, tuple!(2, "hello", 3.14));  // Then `tup` changes

get!(tup; 1) = "world";                     // Direct access the second element of `tup`
assert_eq!(tup, tuple!(2, "world", 3.14));

It’s not a problem for nested tuples either:

use tuplez::{get, tuple};

fn push_world(s: &mut String) {
    s.push_str(" world");
}

let mut tup = tuple!(1, tuple!("hello".to_string(), 3.14));
push_world(&mut get!(get!(tup; 1); 0));
assert_eq!(tup, tuple!(1, tuple!("hello world".to_string(), 3.14)));