Skip to the content.

Learning Rust With Entirely Too Many Linked Lists

perface

In this series I will teach you basic and advanced Rust programming entirely by having you implement 6 linked lists. In doing so, you should learn:

这里谈到了是否应该使用 linked list 的情况: https://rust-unofficial.github.io/too-many-lists/index.html

A bad stack

Linked lists are something procedural programmers shouldn’t touch with a 10-foot pole, and what functional programmers use for everything.

why functional programmers have use linked list

It also still suffers from non-uniformly allocating our elements.

为了防止出现private type leak,申明成为 struct 就可以,enum 不行

...
9 |     More(Box<Node>),
  |          ^^^^^^^^^ can't leak private type

Some of you might be thinking “this is clearly tail recursive, and any decent language would ensure that such code wouldn’t blow the stack”. This is, in fact, incorrect! To see why, let’s try to write what the compiler has to do, by manually implementing Drop for our List as the compiler would:

linked list 的默认实现的drop 并不是 tail recursive 的,为此需要手动帮助其实现 因为不是 tail recursive 的,所以在释放的容易 stackoverflow 我感觉,除非有特殊的原因,list 的释放显然不可能是自动分配的,为什么要从这种角度论证

An Ok Singly-Linked Stack

We need to add lifetimes only in function and type signatures:

A Persistent Singly-Linked Stack

In order to get thread safety, we have to use Arc. Arc is completely identical to Rc except for the fact that reference counts are modified atomically.

The reason this is the case is because Rust models thread-safety in a first-class way with two traits: Send and Sync.

Interior mutability types violate this: they let you mutate through a shared reference. There are two major classes of interior mutability: cells, which only work in a single-threaded context; and locks, which work in a multi-threaded context.

A Bad but Safe Doubly-Linked Deque

A Bad Save Deque

WHEN COMMING BACK

从 section 5.4 开始吧

本站所有文章转发 CSDN 将按侵权追究法律责任,其它情况随意。