本文介绍了loop和while true和有什么不一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Rust教程,现在声称while true和,但在现阶段了解并不是很重要.

The Rust tutorial, and now book claim there is a difference between while true and loop, but that it isn't super important to understand at this stage.

while true {

但是,Rust有专门的关键字loop来处理这种情况:

However, Rust has a dedicated keyword, loop, to handle this case:

loop {

Rust的控制流分析对这种构造的处理与对true的处理有所不同,因为我们知道它总是会循环的.在这个阶段要理解的含义的细节并不是很重要,但是通常,我们可以向编译器提供的信息越多,它对安全性和代码生成的作用就越好,因此您在使用时应始终选择循环计划无限循环.

Rust's control-flow analysis treats this construct differently than a while true, since we know that it will always loop. The details of what that means aren't super important to understand at this stage, but in general, the more information we can give to the compiler, the better it can do with safety and code generation, so you should always prefer loop when you plan to loop infinitely.

完成了一些编译器类型的工作后,我想知道在语义上可能存在什么差异,因为编译器发现两者都是无限循环将是微不足道的.

Having done a little bit of compiler-type work, I have to wonder what possible semantic difference there is, since it would be trivial for the compiler to figure out both are an infinite loop.

那么,编译器如何区别对待它们?

So, how does the compiler treat them differently?

推荐答案

Reddit上回答了.如您所说,编译器可以对while true作特例,但事实并非如此.既然没有,编译器就不会从语义上推断出while true循环中设置的未声明变量,如果您退出循环,则必须始终对其进行初始化,而对于loop循环则必须进行初始化:

This was answered on Reddit. As you said, the compiler could special-case while true, but it doesn't. Since it doesn't, the compiler doesn't semantically infer that an undeclared variable that's set inside a while true loop must always be initialized if you break out of the loop, while it does for a loop loop:

let x;
loop { x = 1; break; }
println!("{}", x)

完全有效,而

let x;
while true { x = 1; break; }
println!("{}", x);

无法通过指向println中的x的使用可能未初始化的变量"进行编译.在第二种情况下,编译器未检测到循环主体将始终至少运行一次.

fails to compile with "use of possibly uninitialised variable" pointing to the x in the println. In the second case, the compiler is not detecting that the body of the loop will always run at least once.

(当然,我们可以特殊地构造结构while true以使其像现在loop一样工作.我相信这就是Java所做的.)

(Of course, we could special case the construct while true to act like loop does now. I believe this is what Java does.)

这篇关于loop和while true和有什么不一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 22:32