Rust简单整理(c1-c3)
by wqpw
基于官方教程《The Rust Programming Language》
1. Getting Started
Hello, Rust
//main.rs
fn main() {
println!("Hello, world!");
}
rustc main.rs && ./main
Hello, Cargo
cargo --version
cargo new hello_cargo
...
cargo build, cargo build --release
cargo check 只检查能否编译
cargo run 编译及运行
2. Programming a Guessing Game
Cargo.toml
[package]
name = "guessing_game"
version = "0.1.0"
authors = ["Administrator"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.3.14"
main.rs
use std::io;
use std::cmp::Ordering;
use rand::Rng;
fn main() {
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
loop {
println!("Please input your guess.");
let mut guess = String::new();
io::stdin().read_line(&mut guess)
.expect("Failed to read line");
let guess: u32 = match guess.trim().parse() {
Ok(num) => num,
Err(_) => continue,
};
println!("You guessed: {}", guess);
match guess.cmp(&secret_number) {
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}
3. Common Programming Concepts
//variable.rs
fn main() {
let x = 12_3 % 3 + 1 * 4 / 2 + 0x12 - 0o3 + 0b11 + b'a';
println!("The value of x is: {}", x);
let x = '的';
println!("{}", x);
let y = true;
println!("{}", y);
let y = "str";
println!("{}", y);
let x: f64 = 23.3-17.12345;
println!("{}", x);
let tup: (i32, f64, u8) = (500, 6.5, 1);
let tup2 = ("s", 's', 233);
let (a, b, c) = tup;
println!("{} {} {}", a, b, c);
println!("{} {}", tup2.0, tup2.1);
let a = [3; 5]; //33333
let b: [i32; 2] = [4, 5];
let c = ["a", "b"];
println!("{} {} {}", a[0], b[1], c[1]);
}
//fn.rs
fn main() {
a("qaq", five());
let y = {
let x = 3;
let x = x * 2;
x
};
println!("{}", y);
let t = aaa();
a(t.0, t.1);
}
fn a(s: &str, n: i32) {
println!("{} {}", s, n);
}
fn five() -> i32 {
//return 5
5
}
fn aaa() -> (&'static str, i32) {
("qwq", 1)
}
//branch.rs
fn main() {
let n = 3;
if n < 5 {
println!("true");
} else if n == 3 {
println!("false");
} else {
println!("233");
}
let con = true;
let n = if con && !false { //||
5
} else {
6
};
println!("{}", n);
let mut counter = 0;
let result = loop {
counter += 1;
if counter == 10 {
break counter * 2;
}
};
println!("{}", result);
let mut number = 3;
while number != 0 {
println!("{}!", number);
number -= 1;
}
let a = [1, 2, 3, 4, 5];
for e in a.iter().rev() {
println!("{}", e);
}
for i in (0..3) {
println!("a");
}
}