Tuples

Tuples in Rune are fixed-size sequences of values. Similarly to a vector, tuples can contain any sequence of values. But there's no way to change the size of a tuple.

let values = ("Now", "You", "See", "Me");
dbg!(values);

values.2 = "Don't";
values.3 = "!";
dbg!(values);
$> cargo run -- run scripts/book/tuples/tuple_masquerade.rn
("Now", "You", "See", "Me")
("Now", "You", "Don\'t", "!")

The following is a simple example of a function returning a tuple:

fn foo() {
    (1, "test")
}

dbg!(foo());
$> cargo run -- run scripts/book/tuples/basic_tuples.rn
(1, "test")

Tuples can also be pattern matched:

match ("test", 1) {
    ("test", n) => {
        dbg!("the first part was a number:", n);
    }
    _ => {
        dbg!("matched something we did not understand");
    }
}
$> cargo run -- run scripts/book/tuples/tuple_patterns.rn
"the first part was a number:"
1

Using tuples from Rust

Tuples are represented externally as primitive tuple types.

use rune::termcolor::{ColorChoice, StandardStream};
use rune::{Diagnostics, Vm};

use std::sync::Arc;

fn main() -> rune::support::Result<()> {
    let context = rune_modules::default_context()?;
    let runtime = Arc::new(context.runtime()?);

    let mut sources = rune::sources! {
        entry => {
            pub fn calc(input) {
                (input.0 + 1, input.1 + 2)
            }
        }
    };

    let mut diagnostics = Diagnostics::new();

    let result = rune::prepare(&mut sources)
        .with_context(&context)
        .with_diagnostics(&mut diagnostics)
        .build();

    if !diagnostics.is_empty() {
        let mut writer = StandardStream::stderr(ColorChoice::Always);
        diagnostics.emit(&mut writer, &sources)?;
    }

    let unit = result?;

    let mut vm = Vm::new(runtime, Arc::new(unit));
    let output = vm.call(["calc"], ((1u32, 2u32),))?;
    let output: (i32, i32) = rune::from_value(output)?;

    println!("{:?}", output);
    Ok(())
}
$> cargo run --example tuple
(2, 4)