变量

定义 immutable 变量,相当于 js 中的 const 。

  1. let x = String::from("hello");
  2. let y = 5;
  3. println!("{}", x); // hello

定义 multable 变量,相当于 js 中的 let 。

  1. let mut x = String::from("hello");
  2. x.push_str(", world");
  3. println!("{}", x); // hello, world
  4. let mut y = 1;
  5. y = 2;
  6. println!("{}", y); // 2

常用类型

字符串

这种为 literals ,不能修改字符内容

  1. let x = "123123";

如果要能修改字符内容的,需要用 String::from

  1. let mut x = String::from("hello");
  2. x.push(',');
  3. x.push_str("world");
  4. println!("{}", x);

之所以两种写法代表不同,跟 Rust 的内存控制设计有关,如果是 literals ,Rust 会认为这个字符是已知类型、长度的数据,会直接存入 stack 里,而如果是 String 这种,因为内容是可变的,所以不会放到 stack 里,而是把内容存到 heap 中,在 stack 中存的是指向内容的指针。

后面的整型这些因为都是已知类型及长度的,都不会有这种问题。

整型

不指定类型,默认是 i32 ,其中 isize 跟 usize 取决于你电脑多少位的。

  1. let x = 100; // i32
  2. let y: u32 = 100; // u32
  3. let z = b'A'; // u8 ,指 A 这个字符的 byte
  4. let a = 2.0; // f64
  5. let b: f32 = 3.0; // f32

image.pngimage.png

布尔类型

  1. let x: bool = true;

Unicode 字符类型

  1. let c = 'z';
  2. let z = 'ℤ';
  3. let heart_eyed_cat = '😻';

Tuple

  1. let tup: (i32, f64, u8) = (500, 6.4, 1);
  2. // usage
  3. let five_hundred = tup.0;
  4. let six_point_four = tup.1;
  5. let one = tup.2;

Array

Rust 里的 Array 类型是跟 tuple 一样固定大小的,不允许改变,( 这一点跟 JS 中的是不同的!! )如果需要用可变大小的类数组类型,需要用 Vector

  1. let a = [1, 2, 3, 4, 5];
  2. // i32 是类型,后面的 5 是约束长度
  3. let b: [i32; 5] = [1, 2, 3, 4, 5];

入参的数组类型声明是 [T] 的格式

  1. fn test_arr(arr: &[String]) {
  2. arr.len()
  3. }
  4. fn main() {
  5. let arr = [ String::from("1"), String::from("2") ];
  6. println!("{}", test_arr(&arr));
  7. }

函数

最后一行不带 ; 会视为类似于 return xxx;

  1. fn test(f: u32) -> u32 {
  2. let b = f * 2;
  3. b
  4. }

流程控制

if..else

  1. fn cond_return(b: u8) -> bool {
  2. return if b > 100 { true } else { false }
  3. }

循环

  1. fn test_loop(mut a: u8, mut b: u8) -> (u8, u8) {
  2. // 类似于 while true 了
  3. loop {
  4. if a >= 10 {
  5. break;
  6. }
  7. a += 1;
  8. }
  9. while b < 10 {
  10. b += 1;
  11. }
  12. return (a, b);
  13. }