rust學(xué)習(xí)筆記
rust學(xué)習(xí)筆記
這學(xué)期選了一門rust課,今年上半年呢,由PKU精英團(tuán)隊打造的rust內(nèi)核zroj就要正式上線了,請大家多多支持。
判斷語句和循環(huán)語句
條件不用加括號,形式和python差不多是for x in ...
沒有range,可以用 0..5 表示[0,5)
基礎(chǔ)類型 Fundamental Types
定寬數(shù)字類型
u8~u128 : 無符號整數(shù)
i8~i128 : 有符號整數(shù)
f32~f64 : 浮點(diǎn)數(shù)
表示一個數(shù)可以加后綴: 123i8,也可以類型推斷
可以使用下劃線對數(shù)字進(jìn)行任意分組
使用as來進(jìn)行類型轉(zhuǎn)換:
assert_eq!( 10_i8 as u16, 10_u16);
assert_eq!( 2525_u16 as i16, 2525_i16);
assert_eq!( -1_i8 as u8, 255_u8); //overflow
在debug模式下整數(shù)溢出會panic,release模式則不會。
可以使用wrapping operations進(jìn)行合法的溢出操作
fn main() {
assert_eq!(100_u16.wrapping_mul(200), 20000);
}
一些特殊值:
f64::MAX
f64::MIN
f64::INFINITY //inf
f64::NEG_INFINITY
f64::NAN
在f64::const 里有一些常數(shù)
打印方法:
println!("{:.20}", PI); // 輸出20位
size_of : 獲得類型寬度
char
和c++一樣是4字節(jié)
把u32值轉(zhuǎn)換為char值:std::char::from_u32
tuple
let t = (1, false, 32.01);
// t1是一個元組類型的變量;t1的準(zhǔn)確類型是(i64, bool, f32)
let t1:(i64, bool, f32) = (t.0, t.1, t.2);
// t.0, t.1, t.2: 訪問元組t中的第1, 第2, 第3個值
無返回值的函數(shù)返回零元組
指針類型 pointer types
引用 Reference
在前面加上&,表示內(nèi)存地址
// 變量value的類型: i32
let value: i32 = 123;
// &value: 一個引用類型的值
// 變量refer的類型: &i32
let refer = &value;
去引用:加上*,讀取該地址的值
只讀引用:ref = &value 不能修改*ref
可變引用:ref = &mut value 可以修改*ref
Box
box把值存放在堆(heap)中
棧:程序的工作現(xiàn)場,空間有限但訪問效率高
堆:一個倉庫,空間大但訪問效率較低
fn main() {
let t = 2022;
let b = Box::new(t);
let mut c: Box<i32> = Box::new(t);
*c = 2023;
// print b's value
println!("{:p}", b); // 0x*******
// print b's pointed value
println!("{}", b); //2022
// print c's pointed value
println!("{}", c); //2023
}
Box::new(value) :申請一個地址
內(nèi)存管理
一個程序至少包含一個進(jìn)程,一個進(jìn)程包含多個線程
每一個線程具有自己的一個棧空間,
一個進(jìn)程的所有線程,共享一個堆空間
數(shù)組與vector
array類型:[T; N] (定長)
vector類型:[Vec
slice切片:&[T] &mut[T]
v.len():長度
以下標(biāo)訪問:v[i],從0開始
輸出數(shù)組:println!("{:?}",v);
array
rust聲明數(shù)組必須要初始化:
let a = [1,2,3,4]
let a = [0; 100] //(100個0)
vector
聲明:
let (mut) v = vec![1,2,3,4]
v.insert(position,value)
v.remove(position)
v.push()
v.pop()
這里內(nèi)部實(shí)現(xiàn)是沒有平衡樹的,時間復(fù)雜度較高。
內(nèi)存包含一堆指針,一個len,一個capacity
slice
fn main() {
let a: [u16; 4] = [0, 1, 2, 3];
let v: Vec<u16> = vec![0, 1, 2, 3, 4];
// sa 是一個類型為 &[u16] 的 slice
// 包含數(shù)組 a 中位置區(qū)間[0, 2)上的元素
let sa: &[u16] = &a[0..2];
// sa 是一個類型為 &[u16] 的 slice
// 包含向量 v 中位置區(qū)間[1, 4)上的元素
let sv: &[u16] = &v[1..4];
println!("{:?}", sa); //=> [0, 1]
println!("{:?}", sv); //=> [1, 2, 3]
}
當(dāng)在array或vector上調(diào)用slice上的方法時,編譯器會自動把a(bǔ)rray或vector轉(zhuǎn)換為slice:如reverse()和sort()
string
同樣使用反斜杠轉(zhuǎn)義,但換行可以直接換行(編輯器里)
raw string
不進(jìn)行任何轉(zhuǎn)義
let raw_string= r"C:\Program Files\path\to\file";
如果想加入雙引號,則加上三個#表示開頭和結(jié)束
let raw_string= r###""C:\Program Files\path\to\file""###;
string 和 &str
&str = string slice
使用 "Hello".to_string(); 和 String::from("World"); 創(chuàng)建string
&str的len()返回字節(jié)數(shù),使用.chars().count()返回字符數(shù)量
format!()
和println!相同,返回一個String值
let a1 = format!("test");
let a2 = format!("hello {}", "world!");
let a3 = format!("x = {x}, y = {y}", y = 10, x = 30);
println!("{}", a1); //=> test
println!("{}", a2); //=> hello world!
println!("{}", a3); //=> x = 30, y = 10
.concat
就是concat
.join
concat中間加一個分隔符(放在第二個參數(shù))
mutable String 和 mutable &str
除了vector的method,還有push_str等等method
但是不能通過integer下標(biāo)改變
其他一些常用方法
fn main() {
println!("{}", "Hello, world!".contains("world")); //=> true
println!("{}", "Hello, world!".replace("world", "dog")); //=> Hello, dog!
println!("{}", " Hello \n ".trim() == "Hello"); //=> true(去除首尾空白)
for word in "Hello world and dog".split(" ") {
println!("{}", word); //=> Hello
} //=> world
} //=> and
//=> dog
type關(guān)鍵字
type Bytes = Vec;
相當(dāng)于c++里的typedef
struct 和 enum
struct
語法:
struct Image {
size: (uszie, usize),
pixels: Vec<u32>
}
let image = Image {
pixels: vec![0; width * height],
size: (width, height)
};
在struct上附著/關(guān)聯(lián)方法
使用impl關(guān)鍵字,還有&self關(guān)鍵字(跟python差不多)
注意加上函數(shù)返回值類型
enum
和haskell很像,不用給出值,在內(nèi)存中被表示為一個整數(shù)
enum Ordering {
Less,
Equal,
Greater
}
也可以帶參數(shù):
enum Color {
RGB(u8, u8, u8),
Gray(u8)
}
let a = Color::RGB(63, 127, 255);
let b = Color::RGB(63, 63, 63);
let c = Color::Gray(127);
在enum上附著/關(guān)聯(lián)方法
impl Ordering {
fn is_eq(self) -> bool {
if self == Ordering::Equal {
true
} else {
false
}
}
}
使用match關(guān)鍵字:
impl Color {
fn is_gray(&self) -> bool {
match self {
Color::Gray(_) => true,
Color::RGB(a, b, c) =>
if a == b && b == c {
true
} else {
false
}
}
}
}
std::option::Option
這不是我們haskell的Maybe嗎!
pub enum Option<T>{
None,
Some(T),
}

浙公網(wǎng)安備 33010602011771號