语句与表达式
示例
1. fn main() {
2. let x = 5u32;
4. let y = {
5. let x_squared = x * x;
6. let x_cube = x_squared * x;
8. // 下面表达式的值将被赋给 `y`
9. x_cube + x_squared + x
10. };
12. let z = {
13. // 分号让表达式变成了语句,因此返回的不再是表达式 `2 * x` 的值,而是语句的值 `()`
14. 2 * x;
15. };
17. println!("x is {:?}", x);
18. println!("y is {:?}", y);
19. println!("z is {:?}", z);
20. }
练习
- 🌟🌟
1. // 使用两种方法让代码工作起来
2. fn main() {
3. let v = {
4. let mut x = 1;
5. x += 2
6. };
8. assert_eq!(v, 3);
9. }
- 🌟
2. fn main() {
3. let v = (let x = 3);
5. assert!(v == 3);
6. }
- 🌟
2. fn main() {
3. let s = sum(1 , 2);
4. assert_eq!(s, 3);
5. }
7. fn sum(x: i32, y: i32) -> i32 {
8. x + y;
9. }
你可以在这里找到答案(在 solutions 路径下)
