zwvista

导航

Rust语言学习笔记(7)

Box<T>

Box<T> 是一个独占资源的智能指针

let b = Box::new(5);
println!("b = {}", b);
// 递归类型
enum List {
    Cons(i32, Box<List>),
    Nil,
}
use List::{Cons, Nil};
let list = Cons(1,
    Box::new(Cons(2,
        Box::new(Cons(3,
            Box::new(Nil))))));
// Box<T>和引用类型一样支持解引用
// 原因是实现了 Deref 特质
let x = 5;
let y = &x;
let z = Box::new(x);
assert_eq!(5, x);
assert_eq!(5, *y);
assert_eq!(5, *z);

Deref 特质

// 自定义类型实现 Deref 特质
struct MyBox<T>(T);
impl<T> MyBox<T> {
    fn new(x: T) -> MyBox<T> {
        MyBox(x)
    }
}
use std::ops::Deref;
impl<T> Deref for MyBox<T> {
    type Target = T;
    fn deref(&self) -> &T {
        &self.0
    }
}
let x = 5;
let y = MyBox::new(x);
assert_eq!(5, x);
assert_eq!(5, *y);

强制解引用(Deref coercion)

fn hello(name: &str) {
    println!("Hello, {}!", name);
}
let m = MyBox::new(String::from("Rust"));
hello(&m); // hello(&(*m)[..]);

强制解引用的条件:

  • T: Deref<Target=U> 时从 &T&U
  • T: DerefMut<Target=U> 时从 &mut T&mut U
  • T: Deref<Target=U> 时从 &mut T&U

Drop 特质

// 自定义类型实现 Drop 特质
struct CustomSmartPointer {
    data: String,
}
impl Drop for CustomSmartPointer {
    fn drop(&mut self) {
        println!("Dropping CustomSmartPointer with data `{}`!", self.data);
    }
}
let c = CustomSmartPointer { data: String::from("my stuff") };
let d = CustomSmartPointer { data: String::from("other stuff") };
println!("CustomSmartPointers created.");
/*
CustomSmartPointers created.
Dropping CustomSmartPointer with data `other stuff`!
Dropping CustomSmartPointer with data `my stuff`!
*/
let c = CustomSmartPointer { data: String::from("some data") };
println!("CustomSmartPointer created.");
drop(c);
println!("CustomSmartPointer dropped before the end of main.");
/*
CustomSmartPointer created.
Dropping CustomSmartPointer with data `some data`!
CustomSmartPointer dropped before the end of main.
*/

Rc<T>

Rc<T> 是一个带引用计数器的智能指针

enum List {
    Cons(i32, Rc<List>),
    Nil,
}
use self::List::{Cons, Nil};
use std::rc::Rc;
let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil)))));
println!("count after creating a = {}", Rc::strong_count(&a)); // strong_count == 1
let b = Cons(3, Rc::clone(&a));
println!("count after creating b = {}", Rc::strong_count(&a)); // strong_count == 2
{
    let c = Cons(4, Rc::clone(&a));
    println!("count after creating c = {}", Rc::strong_count(&a)); // strong_count == 3
}
println!("count after c goes out of scope = {}", Rc::strong_count(&a)); // strong_count == 2

Cell<T>

Cell<T> 在运行期改变内部的值

let x = Cell::new(1);
let y = &x;
let z = &x;
x.set(2);
y.set(3);
z.set(4);
println!("{}", x.get());
// 相当于以下代码的效果(编译会出错)
let mut x = 1;
let y = &mut x;
let z = &mut x;
x = 2;
*y = 3;
*z = 4;
println!("{}", x);

RefCell<T>

RefCell<T> 在运行期实施借用原则

// 可以有多个不变借用
let a = RefCell::new(15);
let b = a.borrow();
let c = a.borrow();
println!("Value of b is : {}",b);
println!("Value of c is : {}",c);
// 不能同时有不变借用和可变借用
let a = RefCell::new(10);
let b = a.borrow();
let c = a.borrow_mut(); // cause panic.
// 可以有一个可变借用
let a = RefCell::new(15);
let b = a.borrow_mut();
println!("Now, value of b is {}",b);
// 不能有多个可变借用
let a = RefCell::new(15);
let b = a.borrow_mut();
let c = a.borrow_mut(); // cause panic.

链接

Wrapper Types in Rust: Choosing Your Guarantees
Rust Smart Pointers

Rust by Example
Rust Cookbook

posted on 2018-08-19 23:48  zwvista  阅读(290)  评论(0编辑  收藏  举报