rust 入门

hello rust

fn main() {
    println!("Hello, world!");
}

从hello world入手,rust的语法是比较简洁。 在mac os中,我们习惯使用docker来快速部署环境。到https://hub.docker.com/查找rust,我们选择第一个,然后安装它:

docker pull scorpil/rust

然后在本地映射一个目录:

docker run -it --rm -v /Users/YOURHOMEDIR/Learn/rust:/someName scorpil/rust

进入docker, cd /srv就可以到你的本地对应的目录。rust 也许是近代设计的新语言,包设计,目录结构都比较科学。如果我们学习的时候,也能像开发一样,是挺好的,rust也觉得这样不错,新建一个项目只要一个命令,cargo new NAME。如果你没有指定后面的参数--bin,这是生成一个Lib库。--bin代表是一个二进制的包。

只要记得两三个命令就可以了,

cargo new PROJECT --bin

cargo run

cargo build

下面开始简介:划重点

突然发现没什么好记的:

第一、

1. rust所有变量都是默认不可变。要改变要加mut关键字。

2. 变量是可以覆盖的

let a = 1;

let a = 2;

但是let不能丢

第二、格式化有点简洁,只要挖个坑{}就行。

 println!("{}, {}!", "Hello", "world"); // Hello, world!
 println!("{0}, {1}!", "Hello", "world"); // Hello, world!
 println!("{greeting}, {name}!", greeting="Hello", name="world"); // Hello, world!

第三、函数返回有点省,函数默认返回一个空的tuple。

//Returning
fn plus_one(a: i32) -> i32 {
    a + 1 //no ; means an expression, return a+1
}

如果加了return反而是不建议的 :(

第四、arrays和tuples都是固定长度。

arrays

let a = [1, 2, 3]; // a[0] = 1, a[1] = 2, a[2] = 3
let mut b = [1, 2, 3];

let c: [int; 3] = [1, 2, 3]; //[Type; NO of elements]

let d: ["my value"; 3]; //["my value", "my value", "my value"];

let e: [i32; 0] = []; //empty array

tuples

let a = (1, 1.5, true, 'a', "Hello, world!");
// a.0 = 1, a.1 = 1.5, a.2 = true, a.3 = 'a', a.4 = "Hello, world!"

let b: (i32, f64) = (1, 1.5);

let (c, d) = b; // c = 1, d = 1.5
let (e, _, _, _, f) = a; //e = 1, f = "Hello, world!", _ indicates not interested of that item

let g = (0,); //single-element tuple

第五、流程控制好简洁。

let team_size = 7;
let team_size_in_text = if team_size < 5 {
    "Small" //⭐️no ;
} else if team_size < 10 {
    "Medium"
} else {
    "Large"
};

第六、match是个好东西

let tshirt_width = 20;
let tshirt_size = match tshirt_width {
    16 => "S", // check 16
    17 | 18 => "M", // check 17 and 18
    19 ... 21 => "L", // check from 19 to 21 (19,20,21)
    22 => "XL",
    _ => "Not Available",
};
println!("{}", tshirt_size); // L

第七、循环

let mut a = 1;
while a <= 10 {
    println!("Current value : {}", a);
    a += 1; //no ++ or -- in Rust
}

while, for, loop 循环几乎都长得差不多,多一个label可以标记中断

let mut c1 = 1;
'outer_while: while c1 < 6 { //set label outer_while
    let mut c2 = 1;
    'inner_while: while c2 < 6 { 
        println!("Current Value : [{}][{}]", c1, c2);
        if c1 == 2 && c2 == 2 { break 'outer_while; } //kill outer_while
        c2 += 1;
    }
    c1 += 1;
}

来自: https://medium.com/learning-rust/rust-basics-e73304ab35c7