Rust 中元组的求值顺序是什么? [英] What is the evaluation order of tuples in Rust?

查看:71
本文介绍了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!(),
    }
}

它输出 y = 1, z = 2 还是 y = 2, z = 1?Rust Playground 在稳定版 1.32.0 上建议使用前者,但如果我多次运行它、重新编译编译器、更改编译器版本等,它可能会改变.

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)?

推荐答案

是的,元组的求值顺序保证是从左到右(这也意味着深度优先,因为必须完全构造值).

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).

不幸的是,这从未在我能找到的任何地方明确说明,但可以从 Rust 强大的向后兼容性保证中推断出来.对评估顺序进行更改可能会导致过多的损坏而无法认真考虑.

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.

另见:

这篇关于Rust 中元组的求值顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆