概览

基本概念

基本概念

Rust 定义变量、函数和数据结构

Rust 定义变量、函数和数据结构

控制流程

控制流程

例子

下载 url 为 md 文件

terminal 输入 cargo run -- https://www.rust-lang.org rust.md

即是把 https://www.rust-lang.org 下载到 rust.md

Cargo.toml

1
2
3
4
5
6
7
8
9
10
[package]
name = "scrape_url"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
reqwest = { version = "0.11", features = ['blocking'] }
html2md = "0.2"

main.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
use std::fs;

fn md_params() -> Result<(String, String), Box<dyn std::error::Error>> {
let url = std::env::args().nth(1).expect("Missing argument");
let output = std::env::args().nth(2).expect("Missing argument");
Ok((url, output))
}

fn main() {
// let url = "https://www.rust-lang.org/";
// let output = "rust.md";

let result = md_params();

match result {
Ok((url, output)) => {
println!("Fetching url: {}", url);
let body = reqwest::blocking::get(url).unwrap().text().unwrap();

println!("Converting html to markdown...");
let md = html2md::parse_html(&body);

println!("Converted markdown has been saved in {}.", output);
fs::write(output, md.as_bytes()).unwrap();
}
Err(err) => {
println!("Error: {}", err.to_string());
}
}
}

费波纳基数列

main.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
fn next_fiber(a: &mut i32, b: &mut i32) {
let c = *a + *b;
*a = *b;
*b = c;
}

fn fib_loop(n: u8) {
let mut a = 1;
let mut b = 1;
let mut i = 2u8;
loop {
// let c = a + b;
// a = b;
// b = c;
next_fiber(&mut a, &mut b);
i += 1;
println!("next val is {}", b);
if i >= n {
break;
}
}
}
fn fib_while(n: u8) {
let (mut a, mut b, mut i) = (1, 1, 2);
while i < n {
// let c = a + b;
// a = b;
// b = c;
next_fiber(&mut a, &mut b);
i += 1;
println!("next val is {}", b);
}
}
fn fib_for(n: u8) {
let (mut a, mut b) = (1, 1);
for _i in 2..n {
// let c = a + b;
// a = b;
// b = c;
next_fiber(&mut a, &mut b);
println!("next val is {}", b);
}
}
fn main() {
let n = 10;
fib_loop(n);
fib_while(n);
fib_for(n);
}