From 特征允许一种类型定义如何从另一种类型显式地转换,提供了一种类型到另一种类型的单向转换。与 From 特征相对应,Into 特征通常用于相同的转换,实际上当类型实现了 From,Rust 自动为类型提供 Into 实现。两个特征让类型转换变得简单而且类型安全,无需手动处理转换逻辑。
1 2 3 4 5 6 7 8 9 10 11 12 13
structNumber { value: i32, } // 为 `Number` 实现 `From<i32>` implFrom<i32> for Number { fnfrom(item: i32) -> Self { Number { value: item } } } let num = Number::from(30); println!("The number is: {}", num.value); let int = 5; let num: Number = int.into();
自动化测试
在使用Rustlings的过程中深刻体会到了Rust内置测试支持的强大之处,无需额外的库就可以编写和运行测试。使用 #[test] 属性标记测试函数,然后使用 cargo test 命令运行所有测试。在 Java 中,即使是未使用的测试代码也可能因为类加载等原因对应用性能有轻微影响,但是Rust 的测试构建只在需要时添加测试代码,不影响生产代码的性能。
letmut arr = vec![1, 2, 3]; letmut i = 0; for elem in &arr { println!("{}",elem); if i == 1 { arr.push(6); } i += 1; }
编译器会拒绝通过,报错如下。
1 2 3 4 5 6 7 8 9 10 11
error[E0502]: cannot borrow `arr` as mutable because it is also borrowed as immutable --> src\main.rs:38:13 | 35 | for elem in &arr { | ---- | | | immutable borrow occurs here | immutable borrow later used here ... 38 | arr.push(6); | ^^^^^^^^^^^ mutable borrow occurs here