- 学习原则:对于这样一个语法相对复杂的语言,用起来要守正出奇,常规的语言表达方式为主,偏门的为辅。学习起来要循序渐进,在实践中不断深入,毕竟不是一开始就使用全部特性,所以可以在实践中不断加深对专有新特性的理解
- 对结构体做修改的方法,self参数一定得是,否则本地变量无法借用
fn update(&mut self){ self.field= new_value; }
- Option的实体对象怎么可变借用出来ops1.as_mut()
let muttable_value=option1.as_mut().unwrap()
- Vector做可变遍历
vec1.iter_mut(); vec1.get_mut(index)
- error[E0499]: cannot borrow `self.om_2_ts` as mutable more than once at a time
error[E0499]: cannot borrow `self.om_2_ts` as mutable more than once at a time 130 | self.handle_market_response(self.om_2_ts.as_mut().unwrap().pop_front().unwrap().clone()) | ---- ---------------------- ^^^^^^^^^^^^ second mutable borrow occurs here | | | | | first borrow later used by call | first mutable borrow occurs here
语句分拆即可
let book_event = self.om_2_ts.as_mut().unwrap().pop_front().unwrap().clone();
self.handle_market_response(book_event)
- 测试代码里面被
#[test]
属性标记了函数会被认为是main函数,此类函数不能有特殊返回值签名 - 关于可变不共享的一个case,下面的代码在1.42版本可以正常运行,但如果最后那两个赋值语句换个个,就会出现" assignment to borrowed `i` occurs here"的错误,证明p1在赋值完以后借用就已经释放了,借用会在它最后一次出现的地方"还"回去,实际上这个表现已经使《深入浅出Rust》中的不少关于可变不共享的错误范例代码可以正常运行了,根本原因NLL非词法作用域使p1的作用域更加智能了
fn main() { let mut i =0; let p1 = &mut i; *p1 =2; i=1; }
8. 基于Tokio的TimeInterval
pub fn time_interval<F>(millsecond:u64,f:F)->task::JoinHandle<()> where F:Fn()->Result<(),()>, F: Sync + 'static, F: Send + 'static, { tokio::spawn(async move { let mut interval = tokio::time::interval(Duration::from_millis(millsecond)); interval.tick().await; let start = Instant::now(); //println!("time:{:?}", start); loop { interval.tick().await; match f(){ Ok(())=>{}, Err(err)=> break, }; println!("time1:{:?}", start.elapsed()); } }) }
9.上面函数返回的这个JoinHandle说定Drop以后,并不使内部的Task结束运行,官方的源文档解释如下
A JoinHandle detaches the associated task when it is dropped, which means that there is no longer any handle to the task, and no way to join on it.