变量
定义 immutable 变量,相当于 js 中的 const 。
let x = String::from("hello");let y = 5;println!("{}", x); // hello
定义 multable 变量,相当于 js 中的 let 。
let mut x = String::from("hello");x.push_str(", world");println!("{}", x); // hello, worldlet mut y = 1;y = 2;println!("{}", y); // 2
常用类型
字符串
这种为 literals ,不能修改字符内容
let x = "123123";
如果要能修改字符内容的,需要用 String::from
let mut x = String::from("hello");x.push(',');x.push_str("world");println!("{}", x);
之所以两种写法代表不同,跟 Rust 的内存控制设计有关,如果是 literals ,Rust 会认为这个字符是已知类型、长度的数据,会直接存入 stack 里,而如果是 String 这种,因为内容是可变的,所以不会放到 stack 里,而是把内容存到 heap 中,在 stack 中存的是指向内容的指针。
后面的整型这些因为都是已知类型及长度的,都不会有这种问题。
整型
不指定类型,默认是 i32 ,其中 isize 跟 usize 取决于你电脑多少位的。
let x = 100; // i32let y: u32 = 100; // u32let z = b'A'; // u8 ,指 A 这个字符的 bytelet a = 2.0; // f64let b: f32 = 3.0; // f32
布尔类型
let x: bool = true;
Unicode 字符类型
let c = 'z';let z = 'ℤ';let heart_eyed_cat = '😻';
Tuple
let tup: (i32, f64, u8) = (500, 6.4, 1);// usagelet five_hundred = tup.0;let six_point_four = tup.1;let one = tup.2;
Array
Rust 里的 Array 类型是跟 tuple 一样固定大小的,不允许改变,( 这一点跟 JS 中的是不同的!! )如果需要用可变大小的类数组类型,需要用 Vector 。
let a = [1, 2, 3, 4, 5];// i32 是类型,后面的 5 是约束长度let b: [i32; 5] = [1, 2, 3, 4, 5];
入参的数组类型声明是 [T] 的格式
fn test_arr(arr: &[String]) {arr.len()}fn main() {let arr = [ String::from("1"), String::from("2") ];println!("{}", test_arr(&arr));}
函数
最后一行不带 ; 会视为类似于 return xxx;
fn test(f: u32) -> u32 {let b = f * 2;b}
流程控制
if..else
fn cond_return(b: u8) -> bool {return if b > 100 { true } else { false }}
循环
fn test_loop(mut a: u8, mut b: u8) -> (u8, u8) {// 类似于 while true 了loop {if a >= 10 {break;}a += 1;}while b < 10 {b += 1;}return (a, b);}

