cargo,rust基础笔记0

cargo

1
2
3
4
5
cargo new "project_name"
cargo build
cargo run
cargo test
cargo build --release
  • std::rc reference counted
  • std::cell::RefCell
1
2
3
4
5
6
7
use std::rc::Rc;
let my_rc = Rc::new(());
Rc::downgrade(&my_rc);

let foo = Rc::new(vec![1.0,2.0,3.0]);
let a = foo.clone();
let b = Rc::clone(&foo);

Borrowing

1
2
3
4
5
6
7
8
9
10
11
fn foo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
// do stuff with v1 and v2

// return the answer
42
}

let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3];

let answer = foo(&v1, &v2);

Rules about borrowing in Rust

  1. any borrow must last for a scope no greater than that of the owner
  2. you may have one or the other of these two kinds of borrows, but not both at the same time
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
enum Coin {
Penny,
Nickel,
Dime,
Quarter,
}
fn value_in_cents(coin: Coin) -> u8 {
match coin {
Coin::Penny => {
println!("Lucky penny!");
1
},
Coin::Nickel => 5,
Coin::Dime => 10,
Coin::Quarter => 25,
}
}
1
2
3
4
5
6
7
8
9
10
fn plus_one(x: Option<i32>) -> Option<i32> {
match x {
None => None,
Some(i) => Some(i + 1),
}
}

let five = Some(5);
let six = plus_one(five);
let none = plus_one(None);
if let 简单控制流
1
2
3
4
5
6
7
8
9
10
11
12
13
14
let some_u8_value = Some(0u8);
match some_u8_value {
Some(3) => println!("three"),
_ => (),
}
if let Some(3) = some_u8_value {
println!("three");
}
let mut count = 0;
if let Coin::Quarter(state) = coin {
println!("State quarter from {:?}!", state);
} else {
count += 1;
}

使用pub来使得mod、结构体、函数共有。

使用super来调用父模块的东西

1
2
3
4
5
6
7
8
9
10
fn serve_order() {}

mod back_of_house {
fn fix_incorrect_order() {
cook_order();
super::serve_order();
}

fn cook_order() {}
}
使用struct 来定义结构体成员变量,使用impl来定义结构方法
使用trait关键字定义一个接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
trait Area{
fn area(&self) -> f64;
}

struct Circle{
r : f64;
}
impl Area for Circle{
fn area(&self) -> f64{
(3.14 * self.r)
}
}
fn main(){
let r = Circle{r :10.5};
println!("area={:?}",r.area());
}

std::include

1
2
3
4
let my_string = include!("monkeys.in");
mod math{
include!("math.rs");
}

mod math;

泛型数据类型