gpt4 book ai didi

rust - Rust 元组参数的执行顺序是什么?

转载 作者:行者123 更新时间:2023-12-04 05:34:40 30 4
gpt4 key购买 nike

如下代码所示,我想封装一个定时函数,返回一个闭包的结果和执行时间。

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()))
}
但是不知道tuple参数的执行顺序是不是从左到右,也就是能否简化为如下代码:
pub fn measure_time_with_value<T>(f: impl FnOnce() -> T) -> (T, Duration) {
Instant::now().pipe(|s| (f(), s.elapsed()))
}

最佳答案

来自 Rust reference, chapter "Expressions", subsection "Evaluation order of operands" (由我突出显示):

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())
);

所以是的,因为元组表达式的评估保证从左到右,您的代码可以按照您描述的方式进行简化。

关于rust - Rust 元组参数的执行顺序是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68618395/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com