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语言学习笔记(7)的更多相关文章
- Rust语言学习笔记(5)
Structs(结构体) struct User { username: String, email: String, sign_in_count: u64, active: bool, } let ...
- Rust语言学习笔记(6)
Traits(特质) // 特质 pub trait Summary { fn summarize(&self) -> String; } pub struct NewsArticle ...
- Rust语言学习笔记(4)
Variables and Mutability(变量和可变性) 变量声明有三种:不变量(运行期的常量),变量以及(编译期的)常量. 变量可以重复绑定,后声明的变量覆盖前面声明的同名变量,重复绑定时可 ...
- HTML语言学习笔记(会更新)
# HTML语言学习笔记(会更新) 一个html文件是由一系列的元素和标签组成的. 标签: 1.<html></html> 表示该文件为超文本标记语言(HTML)编写的.成对出 ...
- 2017-04-21周C语言学习笔记
C语言学习笔记:... --------------------------------- C语言学习笔记:学习程度的高低取决于.自学能力的高低.有的时候生活就是这样的.聪明的人有时候需要.用笨的方法 ...
- 2017-05-4-C语言学习笔记
C语言学习笔记... ------------------------------------ Hello C语言:什么是程序:程序是指:完成某件事的既定方式和过程.计算机中的程序是指:为了让计算机执 ...
- GO语言学习笔记(一)
GO语言学习笔记 1.数组切片slice:可动态增长的数组 2.错误处理流程关键字:defer panic recover 3.变量的初始化:以下效果一样 `var a int = 10` `var ...
- Haskell语言学习笔记(88)语言扩展(1)
ExistentialQuantification {-# LANGUAGE ExistentialQuantification #-} 存在类型专用的语言扩展 Haskell语言学习笔记(73)Ex ...
- Go语言学习笔记十三: Map集合
Go语言学习笔记十三: Map集合 Map在每种语言中基本都有,Java中是属于集合类Map,其包括HashMap, TreeMap等.而Python语言直接就属于一种类型,写法上比Java还简单. ...
随机推荐
- [UE4]小地图UI设计
一.新建一个名为TestMiniMap的UserWidget用来使用小地图StaticMiniMap. 二.在左侧“User Created”面板中可以看到除自身以外的其他所有用户创建的UserWid ...
- scipy构建稀疏矩阵
from scipy.sparse import csr_matrix import numpy as np indptr = np.array([0, 2, 3, 6]) indices = np. ...
- mysql 取整数或小数或精确位数
select cast(3.1415926 as decimal(9,2))精确到几位 select round(1024.5); 四舍五入 select floor(1024.5);取整数部分 se ...
- oracle查看和替换含不可见字符(空白)
select lengthb('1397256'), dump('1397256') from dual; select ascii('') from dual; ), '') from dua ...
- MySQL中实现DROP USER if EXISTS `test`,即创建新用户时检测用户是否存在
MySQL中实现DROP USER if EXISTS `test`,即创建新用户时检测用户是否存在 版权声明:本文为博主原创文章,欢迎大家转载,注明出处即可.有问题可留言,会尽快回复,欢迎探讨 ...
- Java框架相关
问题及答案来源自<Java程序员面试笔试宝典>第五章 Java Web 5.3 框架 11.什么是IoC? IoC:控制反转(Inverse of Control, IoC),有时候也被称 ...
- python-ddt 数据驱动测试
# @File : learn_ddt.py #-*- coding:utf-8 -*- #本次学习:ddt ---data drive test--数据驱动测试 #1.安装 pip install ...
- [Lua]内存泄漏与垃圾回收
参考链接: http://colen.iteye.com/blog/578146 一.内存泄漏的检测 Lua的垃圾回收是自动进行的,但是我们可以collectgarbage方法进行手动回收.colle ...
- mongodb的聚合aggregate|group|match|project|sort|limit|skip|unwind
聚合 aggregate 聚合(aggregate)主要用于计算数据,类似sql中的sum().avg() 语法 db.集合名称.aggregate([{管道:{表达式}}]) 管道 管道在Unix和 ...
- 2014最新 iOS App 提交上架store 详细流程
http://blog.csdn.net/tt5267621/article/details/39430659