What is the execution order of Rust tuple parameters?

Viewed 478

As shown in the following code, I want to encapsulate a timing function that returns the result and the execution time of a closure.

use tap::prelude::Pipe;
use std::time::{Instant, Duration};

pub fn measure_time_with_value<T>(f: impl FnOnce() -> T) -> (T, Duration) {
    Instant::now().pipe(|s| (f(), s)).pipe(|(f, s)| (f, s.elapsed()))
}

But I don’t know whether the execution order of the tuple parameters is from left to right, that is, whether it can be simplified to the following code:

pub fn measure_time_with_value<T>(f: impl FnOnce() -> T) -> (T, Duration) {
    Instant::now().pipe(|s| (f(), s.elapsed()))
}
1 Answers

From the Rust reference, chapter "Expressions", subsection "Evaluation order of operands" (highlighting by me):

Evaluation order of operands

The following list of expressions all evaluate their operands the same way, as described after the list. Other expressions either don't take operands or evaluate them conditionally as described on their respective pages.

  • Dereference expression
  • Error propagation expression
  • Negation expression
  • Arithmetic and logical binary operators
  • Comparison operators
  • Type cast expression
  • Grouped expression
  • Array expression
  • Await expression
  • Index expression
  • Tuple expression
  • Tuple index expression
  • Struct expression
  • Call expression
  • Method call expression
  • Field expression
  • Break expression
  • Range expression
  • Return expression

The operands of these expressions are evaluated prior to applying the effects of the expression. Expressions taking multiple operands are evaluated left to right as written in the source code.

[...]

For example, the two next method calls will always be called in the same order:

let mut one_two = vec![1, 2].into_iter();
assert_eq!(
    (1, 2),
    (one_two.next().unwrap(), one_two.next().unwrap())
);

So yes, as evaluation of tuple expressions is guaranteed to be from left to right, your code can be simplified in the way you described.

Related