Transformations before assignment in destructing tuples

Finally found a project to use/learn Rust for the first time, first day with Rust!

Is there any way to transform destructed tuple values before assignment to variables?

    fn example() -> (String, Option<String>) {
        ("hELLO".to_string(), None)
    // does not compile
    let (head.to_lowercase(), _tail) = example();

    assert_eq!("hello".to_string(), head)

^ This is what I'd think could work (for methods).

Best working candidate I found (more verbose):

    let (head, _tail) = (|| {
        let (head, tail) = example();

        (head.to_lowercase(), tail)

    assert_eq!("hello".to_string(), head)

Is there any better alternative?

You could just re-define and shadow head, like

let (head, tail) = example();
let head = head.to_lowercase();

You won’t be able to put the to_lowercase method call in to the left-hand-side of the let. In that position only patterns are allowed. Patterns can do a few different things, too, but are generally about destructuring / decomposing / accessing components / dereferencing, and such.


By the way, even for this kind of construction, you wouldn’t need an IIFE in Rust. Simple blocks have return values, too, so this would work as well as

    let (head, _tail) = {
        let (head, tail) = example();

        (head.to_lowercase(), tail)

Also, if you don’t need the tail part, there’s also the “ignore” / wildcard pattern “_”.

// don't need tail
let (head, _) = example();
let head = head.to_lowercase();

And for getting just one field out of a tuple, you can also use the numerical field names (starting from 0 for the first field), like in

// don't need tail, single expression
let head = example().0.to_lowercase();

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.