Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the evaluation order of tuples in Rust?

Tuple elements may have side-effects, and some of them may depend on others. Consider this program:

fn main() {
    let mut v = vec![1, 2];
    match (v.pop(), v.pop()) {
        (Some(z), Some(y)) => println!("y = {}, z = {}", y, z),
        _ => unreachable!(),
    }
}

Does it output y = 1, z = 2 or y = 2, z = 1? A few rounds on the Rust Playground suggests the former on stable 1.32.0, but maybe it would change if I ran it more times, recompiled the compiler, changed compiler versions, etc.

Is there a documented commitment or at least intention to maintain a particular order of evaluation for tuples (e.g. depth-first and left-to-right)?

like image 786
Sage Mitchell Avatar asked Jan 22 '19 17:01

Sage Mitchell


People also ask

How are tuples implemented in Rust?

Tuples are constructed using parentheses () , and each tuple itself is a value with type signature (T1, T2, ...) , where T1 , T2 are the types of its members. Functions can use tuples to return multiple values, as tuples can hold any number of values. // The following struct is for the activity.

How do you iterate through a tuple in Rust?

Because a tuple is technically a struct, we cannot iterate over its elements in a loop. If we want a data container that can be iterated over, it would be better to store our data into an array or a collection (like a HashMap ).

Are tuples mutable in Rust?

In Rust, a tuple is immutable, which means we cannot change its elements once it is created.

What is a tuple rust?

A tuple in rust is a finite heterogeneous compound data type, meaning it can store more than one value at once. In tuples there is no inbuilt method to add elements into a tuple. We can use the index to get the value of a tuple, and we also can not iterate over a tuple using for loop.


1 Answers

Yes, the order of evaluation for tuples is guaranteed to be left-to-right (which also implies depth-first, as the value must be fully constructed).

Unfortunately, this is never stated explicitly anywhere that I can find, but can be inferred from Rust's strong backwards compatibility guarantees. Making a change to evaluation order would likely introduce far too much breakage to ever be seriously considered.

I'd also expect that the optimizer is allowed to make changes when safe to do so. For example, if the expressions in the tuple have no side effects, then reordering them is invisible to the user.

See also:

  • Rust tuple: evaluation order: left -> right?
  • The Rust Reference: Expressions
like image 61
Shepmaster Avatar answered Oct 15 '22 17:10

Shepmaster