#macro #initializing #statement #multiple #variables #mutable #single

var

A macro that allows declaring and initialising multiple mutable variables in a single statement

1 unstable release

Uses old Rust 2015

0.0.1 Feb 17, 2015

#7 in #initializing

MIT/Apache

7KB

var!

Build Status

A Rust macro for declaring and initialising multiple mutable variables in a single statement.

#[macro_use] extern crate var;

var! {
    a = 1,
    b: &str = "foo",
    c = 3.0,
}

a += 1;
b = "bar";
c *= 7.0;

Documentation, crates.io


lib.rs:

A macro to declare multiple mutable variables in one statement.

var! { ... } is a generalised form of let mut x = ...;, allowing for several mutable variables to be declared and initialised at once, inspired by the keyword of the same name in languages like Nim and C#.

Available on crates.io

Grammar

"var! {"
    (
        identifier (":" type)? "=" expression
    )*
"}"

where

  • "..." represents a literal ...
  • (...) is for grouping
  • * is zero-or-more copies of the previous entity, comma separated, with optional trailing comma
  • ? is zero-or-one copies of the pervious entity (i.e. optional)

Notably,

  • var! should always be invoked with {}s or else one will get compile errors (invoking a macro with () and [] mean the its internals are parsed as an expression, but declaring a variable with let is a statement),
  • an initialising expression is required, unlike conventional let,
  • pattern matching cannot be performed.

Examples

#[macro_use] extern crate var;

fn fibonacci(n: u32) -> u64 {
    var! {
        a: u64 = 0,
        b = 1,
    }
    for _ in 0..n {
        let tmp = a + b;
        a = b;
        b = tmp;
    }
    return a
}

fn main() {
    assert_eq!(fibonacci(10), 55);
}

No runtime deps