loop { if something { break }}
该代码会一直运行,直到遇到break(或return,return也会同时返回父函数) 。

文章插图
for
for循环是最简单易用的循环 。它比传统的for循环更容易使用 。
for i in 1..3 {} // for(let i = 1; i < 3; i) // iis not a thing, see things to notefor i in 1..=3 {} // for(let i = 1; i <= 3; i)for i in 1..=var {} // for(let i = 1; i <= var; i)for i in array_or_vec {} // for(let i of array_or_vec) in JS// again, as most other things, uses a trait, here named "iterator"// for some types, you need to call `.iter` or `.into_iter`.// Rust Compiler will usually tell you this.for i in something.iter {}
文章插图
while
很简单的循环 。与其他语言不同,Rust没有do...while , 只有最基础的while 。
while condition { looped;}语法与if一样,只不过内容会循环执行 。

文章插图
打印输出
打印输出可以使用 print! 和 println! 。
!表示这是一个宏(即可以扩展成其他代码的快捷方式),但你不需要过多考虑 。另一个常用的宏是 vec! ,它能利用数组创建 Vec<T> (使用 [] 内的值) 。
这些宏都有一个简单的模板系统 。
● 输出一行使用 println! 。
● 输出一个静态字符串使用 print!("something") 。println!中ln的意思是行 , 也就是说它会添加换行符号(\n) 。console.log会默认添加换行 。
● 要输出一个实现了Display trait的值(绝大多数基本类型都实现了),可以使用 print!("{variable}") 。
● 要输出一个实现了Debug trait的值(可以从Display继承),使用 print!("{variable:?}") 。
● 要输出更复杂的实现了Display trait的内容,使用 print!("{}", variable) 。
● 要输出更复杂的实现了Debug trait的内容,使用 print!("{:?}", variable) 。

文章插图
Trait
Trait是Rust中最难理解的概念之一,也是最强大的概念之一 。
Rust没有采用基于继承的系统(面向对象的继承,或JavaScript基于原型的继承),而是采用了鸭子类型(即,如果一个东西像鸭子一样叫 , 那么它就是鸭子) 。
每个类型都有且只有一个“默认”(或匿名)trait,只能在与该类型同一个模块中实现 。通常都是该类型独有的方法 。
其他的都叫trait 。例如:
trait Duck { fn quack(&self) -> String; /// returns if the duck can jump fn can_jump(&self) -> bool { // default trait implementation. Code cannot have any assumptions about the type of self. false // by default duck cannot jump }}struct Dog; // a struct with empty tupleimpl Dog { // a nameless default trait. fn bark(&self) -> String { String::from("bark!") }}impl Duck for Dog { // implement Duck trait for Dog type (struct) fn quack(&self) -> String { String::from("quark!") } // dog kind of quacks differently}let dog = Dog {};dog.bark;dog.quack;首先,我们定义了trait(在面向对象语言中叫做接口,但它只包含方法或函数) 。然后为给定的类型(上例中为Dog)实现trait 。
一些trait可以自动实现 。常见的例子就是Display和Debug trait 。这些trait要求 , 结构中使用的类型必须要相应地实现Display或Debug 。
相关经验推荐
- 放弃简约风吧!过年回家这样打扮,时髦贵气,美得好高级
- 大地色真是秋天yyds,宋轶一身大地色高级又甜美,不止显白还显瘦
- 怎么从成品尺寸推算坯布幅宽
- 秦始皇如何从吕不韦手中夺权
- 为什么建议男生多穿阔腿裤?看这几位明星就知道了,显瘦、高级、太时尚,还提气质!
- 女生微信网名高级冷酷 微信网名高冷霸气冷酷女
- 自然人从什么时起享有民事权利
- 盘点微胖女生的显瘦穿搭,掌握2个搭配要点,造型高级又有范
- 丈夫酒驾接妻子下班被抓:明天能从电视上看到我吗?
- 春天一句话 春天一句话精选
