RUST
Table of Contents
1. array and slienc
数组类型表示为[T; N],数组的引用类型表示为&[T;N],Slice类型表示为[T],Slice的引用类型表示为&[T]。
2. str String &[] Vec convert
s | to | function |
&str | String | String::from(s) or s.tostring() or s.toowned() |
&str | &[u8] | s.asbytes() |
&str | Vec<u8> | s.asbytes().tovec() |
String | &[u8] | s.asbytes() |
String | &str | s.asstr() or &s |
String | Vec<u8> | s.intobytes() |
&[u8] | &str | std::str::fromutf8(s).unwrap() |
&[u8] | String | String::fromutf8(s).unwrap() |
&[u8] | Vec<u8> | s.tovec() |
Vec<u8> | &str | std::str::fromutf8(&s).unwrap() |
Vec<u8> | String | String::fromutf8(s).unwrap() |
Vec<u8> | &[u8] | &s or s.asslice() |
3. 所有权
fn main() { let s1 = String::from("hello"); let s2 = s1; println!("{}, world!", s2); // println!("{}, world!", s1); }
fn main() { let s = String::from("hello world"); let word = first_word(s); // s.clear(); // error! println!("the first word is: {}", word); } fn first_word(s: String) -> String { s }
fn main() { #[derive(Debug)] struct User { active: bool, username: String, email: String, sign_in_count: u64, } let user1 = User { email: String::from("someone@example.com"), username: String::from("someusername123"), active: true, sign_in_count: 1, }; // let user2 = User { // email: String::from("another@example.com"), // ..user1 // }; let user2 = User { active: user1.active, username: String::from("uset2"), email: String::from("another@example.com"), sign_in_count: user1.sign_in_count, }; println!("{}", user1.email); // 下面这行会报错 println!("{:?}", user2) }
- HITS: no matter with ..user1 or xxx: user1.xxx to create new user with old user, if only fundemantal elements have been copy, the old user can still be available, and the other non-fundemantal attributes also . Otherwise the old user instance and also the non-fundemantal attributes are both not available.
4. test
fn main() { let greetings = ["Hello", "Hola", "Bonjour", "Ciao", "こんにちは", "안녕하세요", "Cześć", "Olá", "Здравствуйте", "chào bạn", "您好"]; for (num, greeting) in greetings.iter().enumerate() { print!("{} : ", greeting); match num { 0 => println!("This code is editable and runnable!"), 1 => println!("Este código es editable y ejecutable!"), 2 => println!("Ce code est modifiable et exécutable!"), 3 => println!("Questo codice è modificabile ed eseguibile!"), 4 => println!("このコードは編集して実行出来ます!"), 5 => println!("여기에서 코드를 수정하고 실행할 수 있습니다!"), 6 => println!("Ten kod można edytować oraz uruchomić!"), 7 => println!("Esse código é editável e executável!"), 8 => println!("Этот код можно отредактировать и запустить!"), 9 => println!("Bạn có thể edit và run code trực tiếp!"), 10 => println!("这段代码是可以编辑并且能够运行的!"), _ => {}, } } }
5. item collections
impl Summary for Post
pub fn notify<T: Summary>(item: &T) { println!("Breaking news! {}", item.summarize()); } // is like pub fn notify(item: &impl Summary) { println!("Breaking news! {}", item.summarize()); }
#[derive(Debug)] enum UiObject { Button, SelectBox, } fn main() { let objects = [ UiObject::Button, UiObject::SelectBox ]; for o in objects { draw(o) } } fn draw(o: UiObject) { println!("{:?}",o); }
6. 特征对象
pub trait Draw { fn draw(&self); } pub struct Button { pub width: u32, pub height: u32, pub label: String, } impl Draw for Button { fn draw(&self) { // 绘制按钮的代码 println!("draw for Button, {}, {}, {}", &self.width, &self.height, &self.label); } } struct SelectBox { width: u32, height: u32, options: Vec<String>, } impl Draw for SelectBox { fn draw(&self) { // 绘制SelectBox的代码 println!("draw for Selectbox {}, {}, {:?}", &self.width, &self.height, &self.options); } } // pub struct Screen { // pub components: Vec<Box<dyn Draw>>, // } // impl Screen { // pub fn run(&self) { // for component in self.components.iter() { // component.draw(); // } // } // } pub struct Screen<T: Draw> { pub components: Vec<T>, } impl<T> Screen <T> where T: Draw { pub fn run(&self) { for component in self.components.iter() { component.draw(); } } } fn main() { let screen = Screen { components: vec![ Box::new(SelectBox { width: 75, height: 10, options: vec![ String::from("Yes"), String::from("Maybe"), String::from("No") ], }), Box::new(Button { width: 50, height: 10, label: String::from("OK"), }), ], }; screen.run(); }
7. mut
7.1. mut example
fnmain() { let x :i32 = 48; let X :i32 = 480; let mut y :&i32 = &x; // y can be redirected from x to X, but y can not change x let z: &mut &i32 = &mut y // z can not be redirected, but z can change y }
7.2. different lifetime
fn main() { struct MutStr<'a, 'b> { s: &'a mut &'b str, } let mut r: &str = "hello"; Mutstr{s: &mut r}.s = "world"; println!("{}", r); }
8. Traits with where
struct Cacher<T, E> where T: Fn(E) -> E, E: Copy, { query: T, value: Option<E>, } impl<T, E> Cacher<T, E> where T: Fn(E) -> E, E: Copy, { fn new(query: T) -> Cacher<T, E> { Cacher { query, value: None } } fn value(&mut self, arg: E) -> E { match self.value { Some(v) => v, None => { let v = (self.query)(arg); self.value = Some(v); v } } } } #[cfg(test)] mod tests { use super::*; #[test] fn call_with_different_values() { let mut c = Cacher::new(|a| a); c.value(1); let v1 = c.value(1); let v2 = c.value(2); assert_eq!(v2, 1); assert_eq!(v2, v1); } #[test] fn call_with_str() { let mut b = Cacher::new(|a| a); let b1 = b.value("test"); assert_eq!("test", b1); } pub fn run_tests_manually() { call_with_different_values(); call_with_str(); } } fn main() { let mut c = Cacher::new(|a| a+2); c.value(1); let v1 = c.value(1); assert_eq!(v1, 3); #[cfg(test)] tests::run_tests_manually(); }