Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Rust loop

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

今天小编给大家分享一下Rust循环如何使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

while 循环

while 循环是最典型的条件语句循环:

实例

fn main() { let mut number = 1; while number != 4 { println!("{}", number); number += 1; } println!("EXIT");}

运行结果:

123EXIT

Rust 语言到此教程编撰之日还没有 do-while 的用法,但是 do 被规定为保留字,也许以后的版本中会用到。

在 C 语言中 for 循环使用三元语句控制循环,但是 Rust 中没有这种用法,需要用 while 循环来代替:

C 语言

int i;for (i = 0; i let mut i = 0;while ifor 循环

for 循环是最常用的循环结构,常用来遍历一个线性数据据结构(比如数组)。for 循环遍历数组:

实例

fn main() { let a = [10, 20, 30, 40, 50]; for i in a.iter() { println!("值为 : {}", i); }}

运行结果:

值为 : 10值为 : 20值为 : 30值为 : 40值为 : 50

这个程序中的 for 循环完成了对数组 a 的遍历。a.iter() 代表 a 的迭代器(iterator),在学习有关于对象的章节以前不做赘述。

当然,for 循环其实是可以通过下标来访问数组的:

实例

fn main() {let a = [10, 20, 30, 40, 50]; for i in 0..5 { println!("a[{}] = {}", i, a[i]); }}

运行结果:

a[0] = 10a[1] = 20a[2] = 30a[3] = 40a[4] = 50loop 循环

身经百战的开发者一定遇到过几次这样的情况:某个循环无法在开头和结尾判断是否继续进行循环,必须在循环体中间某处控制循环的进行。如果遇到这种情况,我们经常会在一个 while (true) 循环体里实现中途退出循环的操作。

Rust 语言有原生的无限循环结构 -- loop:

实例

fn main() { let s = ['R', 'U', 'N', 'O', 'O', 'B']; let mut i = 0; loop { let ch = s[i]; if ch == 'O' { break; } println!("\'{}\'", ch); i += 1; }}

运行结果:

'R''U''N'

loop 循环可以通过 break 关键字类似于 return 一样使整个循环退出并给予外部一个返回值。这是一个十分巧妙的设计,因为 loop 这样的循环常被用来当作查找工具使用,如果找到了某个东西当然要将这个结果交出去:

实例

fn main() { let s = ['R', 'U', 'N', 'O', 'O', 'B']; let mut i = 0; let location = loop { let ch = s[i]; if ch == 'O' { break i; } i += 1; }; println!(" \'O\' 的索引为 {}", location);}

运行结果:

'O' 的索引为 3以上就是"Rust循环如何使用"这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注行业资讯频道。

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report