常见概念

  1. //常量
  2. const MAX: u32 = 100_000;
  3. fn main() {
  4. //不可变
  5. let x = 5;
  6. //可变
  7. let mut v = 6;
  8. v = 7
  9. }

隐藏(Shadowing)

可以作为变量名服用

  1. fn main() {
  2. let x = 5;
  3. let x = x + 1;
  4. let x = x + 2;
  5. println!("{}", x);
  6. }

数据类型

  1. fn main() {
  2. let guess: u32 = "42".parse();
  3. let foo = 98_222;
  4. // 四字节Unicode
  5. let c = 'z';
  6. // 元组与解构
  7. let tup = (6.4, 1, 't');
  8. let (x, y, z) = tup;
  9. let a = [1, 2, 4];
  10. }

函数

  1. fn main() {
  2. let x = foo();
  3. }
  4. fn foo() -> i32 {
  5. 5
  6. }

控制流

  1. fn main() {
  2. let mut x = 5;
  3. let num = if x > 5 {
  4. 5
  5. } else {
  6. 6
  7. };
  8. println!("{}", num);
  9. let r = loop {
  10. x += 1;
  11. if x == 10 {
  12. break x;
  13. }
  14. };
  15. println!("{}", r);
  16. }
  1. fn main() {
  2. let a = [1, 2, 4];
  3. for x in a.iter() {
  4. println!("{}", x)
  5. }
  6. for x in (1..4).rev() {
  7. println!("{}", x)
  8. }
  9. }

结构体

元组结构体

  1. struct Color(i32, i32, i32);

结构体方法

  1. struct Rectangle {
  2. width: u32,
  3. height: u32,
  4. }
  5. impl Rectangle {
  6. fn area(&self) -> u32 {
  7. self.width * self.height
  8. }
  9. }
  10. fn main() {
  11. let rect = Rectangle { width: 3, height: 4};
  12. println!("{}", rect.area());
  13. }

资料

https://github.com/rust-lang-cn/rust-by-example-cn