Skip to content

wufangjie/rust-note2

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

32 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

table of contents

这后面的内容还比较乱, 有时间再整理

易错和小技巧

deref

impl<T: ?Sized> const Deref for &mut T {
    type Target = T;
    fn deref(&self) -> &Self::Target {
	*self // actually this self is &&mut T
    }
}

为某个类型 T impl Deref trait, 可以让我们像引用一样对该类型解引用

  • *T 实际上会被编译器解释成 *(T.deref())
  • deref() 的调用可以用 &* 达到同样的效果 (不会 move out)
  • deref() 返回 &Self::Target 的另一个作用是可以不断 deref 直到达到我们的期望类型

0.. 表示零到无穷

慎用 let _ = y;

目前为止那个博主 (jon gjengset) 翻车过两次, 一个是想用这句触发 drop 但实际上没有 另一次是想验证自己实现的 Rc 是否是 Send 的 这句可能被优化过, 并没有实际的作用 (其实单用一个 y 就可以了)

useful macros

  • unreachable!
  • dbg! (my dbgt!)

retain()

Retains only the elements specified by the predicate This method operates in place, visiting each element exactly once in the original order, and preserves the order of the retained elements.

基本 collection 都实现了 retain, 可以看看官方文档的例子

let mut left = lst[0].clone();
for i in 1..lst.len() {
    left.retain(|x| lst[i].contains(x));
}

std::cmp::Reverse

就是一个简单的 wrapper (要用里面的话直接 .0 就可以, 设置了 pub), 然后反向实现了 PartialOrd, 从而达到反向排序的效果

作用:

  1. 对于不能加负号的反向排序, 而且应该会比加负号快 (不用转换)
  2. 利用这个可以让标准库的 BinaryHeap 可适用最小堆

match pattern/ergonomic

https://doc.rust-lang.org/book/ch18-03-pattern-syntax.html https://doc.rust-lang.org/rust-by-example/flow_control/match.html https://rust-lang.github.io/rfcs/2005-match-ergonomics.html

inner and outer attributes

  • inner attribute, must at the beginning of file (or block?) exclude comments
  • outer means out of the (following) declaration?
  • outer attributes’ annotated items could be structs, enums and unions
#![no_std] // inner attributes
#![allow(dead_code)]

#[allow(dead_code)]
#[derive(Debug)] // outer attributes

visibility

public and private

  1. If an item is public, then it can be accessed externally from some module m if you can access all the item’s ancestor modules from m. You can also potentially be able to name the item through re-exports. See below.
  2. If an item is private, it may be accessed by the current module and its descendants (submodule).

pub(…)

  • pub(in path) makes an item visible within the provided path. path must be an ancestor module of the item whose visibility is being declared.
  • pub(crate) makes an item visible within the current crate.
  • pub(super) makes an item visible to the parent module. This is equivalent to pub(in super).
  • pub(self) makes an item visible to the current module. This is equivalent to pub(in self) or not using pub at all.

分散知识汇总

Cow (Clone on Write)

为了提高性能, 只有当需要写入的时候才 clone, 比如字符串的底层就是这个

pub enum Cow<'a, B>
where
    B: 'a + Owned + ?Sized,
{
    Borrowd(&'a B),
    Owned(<B as Owned>::Owned)

}

all kinds of bounds

T: Trait (trait bound syntax)

T: ‘a

T: ‘a means that all lifetime parameters of T outlive ‘a T: ‘static basically means that T is a type that does not contain any non-‘static references, even nested

T: Trait + ‘a

SubTrait: SuperTrait

‘a: ‘b (lifetime bound)

  • read as ‘a outlives ‘b
  • means that ‘a lasts at least as long as ‘b

https://doc.rust-lang.org/reference/trait-bounds.html#lifetime-bounds

Higher-ranked trait bounds

Trait Object Lifetime Bounds

&dyn Trait + 'a

and/or sugar

oror_elseor_default
unwrap
map
ok
err

by and by_key

byby_key
sort
cmp::max
cmp::min
iterator::max

as_ 或 get_ 前缀的方法

as_ref, as_mut

  • 这两个可能是 AsRef, AsMut 的 trait method
  • 也可能是普通方法, 比如 Option, Result, Pin, pointer

as_deref, as_deref_mut

好像是只有 Option, Result, Pin 有

get_ref

get_mut

这个有时候对应的是 get, 而不是 get_ref

zero cost abstration

经常看到, 可能会有理解的偏差 all of the analysis at compile time. You do not pay any run-time cost for any of these features

rust 的魔法

box 的 drop

unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Box<T, A> {
    fn drop(&mut self) {
        // FIXME: Do nothing, drop is currently performed by compiler.
    }
}

std::intrinsics

intrinsic means it is built in to the compiler, rather than being implemented in Rust library code

实战

Flatten

https://www.youtube.com/watch?v=yozQ9C69pNs

channel

https://www.youtube.com/watch?v=b4mS5UPHh20

sync channels: send 也是阻塞的,因为通道有大小限制 (不至于无限扩大)

async_book

https://rust-lang.github.io/async-book/

timer_future executor

nomicon

第九章 implementing Vec 挺不错的, 循序渐进, 能学到一些关于

指针操作ptr::{read, write, copy}
内存分配alloc::{alloc, realloc, dealloc, Layout}
forget and drop
内存对齐align
ZST

第十章 Arc 和 Mutex (还没有开始写) 都已经看了源码, 就没去看

too many linked list

看了前六章, 挺有意思的 Box 型的链表需要手动循环删除,因为无法实现尾递归 std::mem 的实战 Option 的实战 (as_ref, as_mut, take, map, and_then, as_deref, as_deref_mut) (通过函数调用来约束 lifetime, 避免使用临时变量) Arc/Rc (get_mut 和 try_unwrap 的区别) RefCell 相关, 很难用好, 尤其涉及到 lifetime, 不用深究实际上也很少用 Ref::map, Ref::map_split Iter/IterMut/IntoIter (&mut Option 和 Option<&mut> 区别)

About

不那么入门的 rust 笔记

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages