官术网_书友最值得收藏!

  • Rust Quick Start Guide
  • Daniel Arbuckle
  • 344字
  • 2021-06-10 19:46:05

while loops

while loop is a lot like an if expression. The difference is, instead of checking the condition expression once and then either running the block expression or not, and then being done, a while loop keeps repeating the process until the condition expression produces false. So, if the condition expression results in false right away, the block expression never runs. On the other hand, if the condition expression produces true on the first check, the block expression gets run, and then the condition expression is evaluated again. If it produces true again, the block runs again, and so on, until the condition expression finally produces false.

That means that it's very important for the block expression to change something that affects the condition expression's result. If the condition expression produces true and the block doesn't have any chance of changing that, the program will be stuck looping through that block over and over until the program is forcefully terminated. This is the easiest way to cause your program to freeze.

So, here's a simple while loop:

while i < 3 {
i = i + 1;
println!("While loop {}", i);
}

We're using a variable named i here, which we'll talk about more in the Variables and mutability section of this chapter. For now, just think of i as a name that we can assign different values to at different times, sort of like how we can ask different people to sit in the same chair at different times.

So, we have the while keyword followed by a condition expression. This condition expression uses a variable, which we change the value of in the block expression, so we're not in danger of looping forever. If i starts with the value 0, we should see the block expression run three times: once when i is 0, once when i is 1, and once when i is 2. When i gets to 3, the condition expression produces false as its result (3 is not less than 3), and the loop stops.

主站蜘蛛池模板: 大名县| 北宁市| 庆云县| 双鸭山市| 仙桃市| 潜山县| 瓮安县| 汨罗市| 修武县| 瑞昌市| 文水县| 洪江市| 亚东县| 桦甸市| 襄樊市| 依兰县| 崇信县| 修武县| 太仆寺旗| 灵山县| 平安县| 卓尼县| 香格里拉县| 弥渡县| 澄迈县| 蛟河市| 平塘县| 揭西县| 万全县| 黄冈市| 景东| 金门县| 吉林省| 兴海县| 鞍山市| 台东市| 江源县| 涟水县| 常山县| 温泉县| 广宗县|