文本段,数据段,堆栈段,堆片段
手动,自动,半自动
堆栈
堆
各种bug,内存泄漏
所有权
移动和复制语义
copy特性
clone特性
闭包中的所有权 move||
借用 &, &mut
&self, &mut self ,self
生命周期
‘a
struct xx<‘a, T>{
part: &‘a T
}
生命周期的使用
引用 &T &mut T
原始指针
智能指针
Deref制度和DerefMut
智能指针
use std::rc::Rc;
use std::cell::Cell;
use std::cell::RefCell;
fn main() {
println!("Hello, world!");
//1 struct
let foo1 = Foo(1023);
let bar = &foo1;
println!("foo1:{:?}", foo1);
//2 life time
let a = 10;
let mut num = Number{num:&a};
num.set_num(&111);
println!("{:?}", num.get_num());
//3
let c1 = Cc{num:12};
//box
let box_one = Box::new( Cc{num:22});
let box_one2 = *box_one;
box_ref(box_one2);
//rc
let rc1 = Rc::new(Cc{num:23});
let rc2 = rc1.clone();
println!("rc2 {:?}", *rc2);
println!("rc2 {:?}", Rc::strong_count(&rc2));
//cell
let cell1 = Cell::new( Cc2{num:Box::new(22)});
let hand1 = & cell1;
let hand2 = & cell1;
hand1.set( Cc2{num:Box::new(33)});
hand2.set( Cc2{num:Box::new(55)});
//println!("rc2 {:?}", cell1.get());
//ref cell
let ref_cell1 = RefCell::new( Cc2{num:Box::new(22)});
let hand1 = & ref_cell1;
let hand2 = & ref_cell1;
*hand1.borrow_mut() = Cc2{num:Box::new(33)};
*hand2.borrow_mut() = Cc2{num:Box::new(55)};
let borrow = hand1.borrow();
println!("borrow:{:?}", borrow);
}
fn box_ref<T>(b: T) -> Box<T>{
let a = b;
Box::new(a)
}
#[derive(Debug)]
struct Foo(u32);
struct Number<‘a>{
num:&‘a u8
}
impl<‘a> Number<‘a>{
fn get_num(&self)->&‘a u8{
self.num
}
fn set_num(&mut self, new_number: &‘a u8){
self.num = new_number
}
}
#[derive(Debug)]
struct Cc{
num: u8
}
impl Clone for Cc {
fn clone(&self) -> Self {
Cc{num:self.num}
}
}
impl Drop for Cc{
fn drop(&mut self){
println!("went way {:?}",self.num );
}
}
#[derive(Debug)]
struct Cc2{
num: Box<u32>
}
原文:https://www.cnblogs.com/beckbi/p/14698137.html