|
|
@ -35,36 +35,179 @@ fn main(){
|
|
|
|
因为我们试图同时使用值和值的引用,最终所有权转移和借用一起发生了。所以,这个问题貌似并没有那么好解决,不信你可以回想下自己具有的知识,是否可以解决?
|
|
|
|
因为我们试图同时使用值和值的引用,最终所有权转移和借用一起发生了。所以,这个问题貌似并没有那么好解决,不信你可以回想下自己具有的知识,是否可以解决?
|
|
|
|
|
|
|
|
|
|
|
|
#### 使用ouroboros
|
|
|
|
#### 使用ouroboros
|
|
|
|
|
|
|
|
对于自引用结构体,三方库也有支持的,其中一个就是`ouroboros`,当然它也有自己的限制,我们后面会提到,先来看看该如何使用:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
|
|
|
use ouroboros::self_referencing;
|
|
|
|
|
|
|
|
|
|
|
|
## 玉树临风的自引用
|
|
|
|
#[self_referencing]
|
|
|
|
|
|
|
|
struct SelfRef {
|
|
|
|
|
|
|
|
value: String,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#[borrows(value)]
|
|
|
|
|
|
|
|
pointer_to_value: &'this str,
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn main(){
|
|
|
|
|
|
|
|
let v = SelfRefBuilder {
|
|
|
|
|
|
|
|
value: "aaa".to_string(),
|
|
|
|
|
|
|
|
pointer_to_value_builder: |value: &String| value,
|
|
|
|
|
|
|
|
}.build();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 借用value值
|
|
|
|
|
|
|
|
let s = v.borrow_value();
|
|
|
|
|
|
|
|
// 借用指针
|
|
|
|
|
|
|
|
let p = v.borrow_pointer_to_value();
|
|
|
|
|
|
|
|
// value值和指针指向的值相等
|
|
|
|
|
|
|
|
assert_eq!(s, *p);
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
可以看到,`ouroboros`使用起来并不复杂,就是需要你去按照它的方式创建结构体和引用类型:`SelfRef`变成`SelfRefBuilder`,引用字段从`pointer_to_value`变成`pointer_to_value_builder`,并且连类型都变了。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
在使用时,通过`borrow_value`来借用`value`的值,通过`borrow_pointer_to_value`来借用`pointer_to_value`这个指针。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
看上去很美好对吧?但是你可以尝试着去修改`String`字符串的值试试,`ouroboros`限制还是较多的,但是对于基本类型依然是支持的不错:
|
|
|
|
```rust
|
|
|
|
```rust
|
|
|
|
use std::str;
|
|
|
|
use ouroboros::self_referencing;
|
|
|
|
|
|
|
|
|
|
|
|
struct MyStruct<'a>{
|
|
|
|
#[self_referencing]
|
|
|
|
Buf: Vec<u8>,
|
|
|
|
struct MyStruct {
|
|
|
|
repr: Parsed<'a>
|
|
|
|
int_data: i32,
|
|
|
|
|
|
|
|
float_data: f32,
|
|
|
|
|
|
|
|
#[borrows(int_data)]
|
|
|
|
|
|
|
|
int_reference: &'this i32,
|
|
|
|
|
|
|
|
#[borrows(mut float_data)]
|
|
|
|
|
|
|
|
float_reference: &'this mut f32,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
struct Parsed<'a>{
|
|
|
|
fn main() {
|
|
|
|
name:&'a str
|
|
|
|
let mut my_value = MyStructBuilder {
|
|
|
|
|
|
|
|
int_data: 42,
|
|
|
|
|
|
|
|
float_data: 3.14,
|
|
|
|
|
|
|
|
int_reference_builder: |int_data: &i32| int_data,
|
|
|
|
|
|
|
|
float_reference_builder: |float_data: &mut f32| float_data,
|
|
|
|
|
|
|
|
}.build();
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Prints 42
|
|
|
|
|
|
|
|
println!("{:?}", my_value.borrow_int_data());
|
|
|
|
|
|
|
|
// Prints 3.14
|
|
|
|
|
|
|
|
println!("{:?}", my_value.borrow_float_reference());
|
|
|
|
|
|
|
|
// Sets the value of float_data to 84.0
|
|
|
|
|
|
|
|
my_value.with_mut(|fields| {
|
|
|
|
|
|
|
|
**fields.float_reference = (**fields.int_reference as f32) * 2.0;
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// We can hold on to this reference...
|
|
|
|
|
|
|
|
let int_ref = *my_value.borrow_int_reference();
|
|
|
|
|
|
|
|
println!("{:?}", *int_ref);
|
|
|
|
|
|
|
|
// As long as the struct is still alive.
|
|
|
|
|
|
|
|
drop(my_value);
|
|
|
|
|
|
|
|
// This will cause an error!
|
|
|
|
|
|
|
|
// println!("{:?}", *int_ref);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
fn main(){
|
|
|
|
总之,使用这个库前,强烈建议看一些官方的例子中支持什么样的类型和API,如果能满足的你的需求,就果断使用它,如果不能满足,就继续往下看。
|
|
|
|
|
|
|
|
|
|
|
|
let v = vec!(0065,0066,0067,0068,0069);
|
|
|
|
<!-- 只能说,它确实帮助我们解决了问题,但是一个是破坏了原有的结构,另外就是并不是所有数据类型都支持:它需要目标值的内存地址不会改变,这里的`String`非常适合因此`Vec`动态数组就不适合,因为当内存空间不够时,Rust会重新分配一块空间来存放该数组,这会导致内存地址的改变。 -->
|
|
|
|
let s = str::from_utf8(&v).unwrap();
|
|
|
|
|
|
|
|
println!("{}",s);
|
|
|
|
|
|
|
|
let p = &v[1..=3];
|
|
|
|
|
|
|
|
let s1 = str::from_utf8(p).unwrap();
|
|
|
|
|
|
|
|
println!("{}",s1);
|
|
|
|
|
|
|
|
let par = Parsed{name:s1};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
let new1 = MyStruct{Buf:v,repr:par};
|
|
|
|
#### unsafe实现
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
|
|
|
|
struct SelfRef {
|
|
|
|
|
|
|
|
value: String,
|
|
|
|
|
|
|
|
pointer_to_value: *const String,
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
impl SelfRef {
|
|
|
|
|
|
|
|
fn new(txt: &str) -> Self {
|
|
|
|
|
|
|
|
SelfRef {
|
|
|
|
|
|
|
|
value: String::from(txt),
|
|
|
|
|
|
|
|
pointer_to_value: std::ptr::null(),
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn init(&mut self) {
|
|
|
|
|
|
|
|
let self_ref: *const String = &self.value;
|
|
|
|
|
|
|
|
self.pointer_to_value = self_ref;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn value(&self) -> &str {
|
|
|
|
|
|
|
|
&self.value
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn pointer_to_value(&self) -> &String {
|
|
|
|
|
|
|
|
assert!(!self.pointer_to_value.is_null(), "Test::b called without Test::init being called first");
|
|
|
|
|
|
|
|
unsafe { &*(self.pointer_to_value) }
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
|
|
|
let mut t = SelfRef::new("hello");
|
|
|
|
|
|
|
|
t.init();
|
|
|
|
|
|
|
|
// 打印值和指针地址
|
|
|
|
|
|
|
|
println!("{}, {:p}",t.value(), t.pointer_to_value());
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
在这里,我们在`pointer_to_value`中直接存储原生指针,而不是Rust的引用,因此不再受到Rust借用规则和生命周期的限制,而且实现起来非常清晰、简洁。但是缺点就是,通过指针获取值时需要使用`unsafe`代码,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
当然,上面的代码你还能通过原生指针来修改`String`,但是需要将`*const`修改为`*mut`:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
|
|
|
#[derive(Debug)]
|
|
|
|
|
|
|
|
struct SelfRef {
|
|
|
|
|
|
|
|
value: String,
|
|
|
|
|
|
|
|
pointer_to_value: *mut String,
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
impl SelfRef {
|
|
|
|
|
|
|
|
fn new(txt: &str) -> Self {
|
|
|
|
|
|
|
|
SelfRef {
|
|
|
|
|
|
|
|
value: String::from(txt),
|
|
|
|
|
|
|
|
pointer_to_value: std::ptr::null_mut(),
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn init(&mut self) {
|
|
|
|
|
|
|
|
let self_ref: *mut String = &mut self.value;
|
|
|
|
|
|
|
|
self.pointer_to_value = self_ref;
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn value(&self) -> &str {
|
|
|
|
|
|
|
|
&self.value
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn pointer_to_value(&self) -> &String {
|
|
|
|
|
|
|
|
assert!(!self.pointer_to_value.is_null(), "Test::b called without Test::init being called first");
|
|
|
|
|
|
|
|
unsafe { &*(self.pointer_to_value) }
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
|
|
|
|
let mut t = SelfRef::new("hello");
|
|
|
|
|
|
|
|
t.init();
|
|
|
|
|
|
|
|
println!("{}, {:p}",t.value(), t.pointer_to_value());
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
t.value.push_str(", world");
|
|
|
|
|
|
|
|
unsafe {
|
|
|
|
|
|
|
|
(&mut *t.pointer_to_value).push_str("!");
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
println!("{}, {:p}",t.value(), t.pointer_to_value());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
```
|
|
|
|
|
|
|
|
运行后输出:
|
|
|
|
|
|
|
|
```console
|
|
|
|
|
|
|
|
hello, 0x16f3aec70
|
|
|
|
|
|
|
|
hello, world!, 0x16f3#aec70
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
上面的`unsafe`虽然简单好用,但是它不太安全,是否还有其他选择?还真的有,那就是`Pin`。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#### 无法被移动的Pin
|
|
|
|
|
|
|
|
Pin在后续章节会深入讲解,目前你只需要知道它可以固定住一个值,防止该值的所有权被转移。
|
|
|
|
|
|
|
|
|
|
|
|
## 使用Pin来解决自引用
|
|
|
|
通过开头我们知道,自引用最麻烦的就是创建引用的同时,值的所有权会被转移,而通过Pin就可以很好的防止这一点:
|
|
|
|
Pin在后续章节会深入讲解,目前你只需要知道它可以固定住一个值,防止该值的所有权被转移。通过Pin也可以实现自引用的数据结构:
|
|
|
|
|
|
|
|
```rust
|
|
|
|
```rust
|
|
|
|
use std::marker::PhantomPinned;
|
|
|
|
use std::marker::PhantomPinned;
|
|
|
|
use std::pin::Pin;
|
|
|
|
use std::pin::Pin;
|
|
|
@ -80,21 +223,18 @@ struct Unmovable {
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
impl Unmovable {
|
|
|
|
impl Unmovable {
|
|
|
|
// To ensure the data doesn't move when the function returns,
|
|
|
|
// 为了确保函数返回时数据的所有权不会被转移, 我们将它放在堆上, 唯一的访问方式就是通过指针
|
|
|
|
// we place it in the heap where it will stay for the lifetime of the object,
|
|
|
|
|
|
|
|
// and the only way to access it would be through a pointer to it.
|
|
|
|
|
|
|
|
fn new(data: String) -> Pin<Box<Self>> {
|
|
|
|
fn new(data: String) -> Pin<Box<Self>> {
|
|
|
|
let res = Unmovable {
|
|
|
|
let res = Unmovable {
|
|
|
|
data,
|
|
|
|
data,
|
|
|
|
// we only create the pointer once the data is in place
|
|
|
|
// 只有在数据到位时,才创建指针,否则数据会在开始之前就被转移所有权
|
|
|
|
// otherwise it will have already moved before we even started
|
|
|
|
|
|
|
|
slice: NonNull::dangling(),
|
|
|
|
slice: NonNull::dangling(),
|
|
|
|
_pin: PhantomPinned,
|
|
|
|
_pin: PhantomPinned,
|
|
|
|
};
|
|
|
|
};
|
|
|
|
let mut boxed = Box::pin(res);
|
|
|
|
let mut boxed = Box::pin(res);
|
|
|
|
|
|
|
|
|
|
|
|
let slice = NonNull::from(&boxed.data);
|
|
|
|
let slice = NonNull::from(&boxed.data);
|
|
|
|
// we know this is safe because modifying a field doesn't move the whole struct
|
|
|
|
// 这里其实安全的,因为修改一个字段不会转移整个结构体的所有权
|
|
|
|
unsafe {
|
|
|
|
unsafe {
|
|
|
|
let mut_ref: Pin<&mut Self> = Pin::as_mut(&mut boxed);
|
|
|
|
let mut_ref: Pin<&mut Self> = Pin::as_mut(&mut boxed);
|
|
|
|
Pin::get_unchecked_mut(mut_ref).slice = slice;
|
|
|
|
Pin::get_unchecked_mut(mut_ref).slice = slice;
|
|
|
@ -105,18 +245,48 @@ impl Unmovable {
|
|
|
|
|
|
|
|
|
|
|
|
fn main() {
|
|
|
|
fn main() {
|
|
|
|
let unmoved = Unmovable::new("hello".to_string());
|
|
|
|
let unmoved = Unmovable::new("hello".to_string());
|
|
|
|
// The pointer should point to the correct location,
|
|
|
|
// 只要结构体没有被转移,那指针就应该指向正确的位置,而且我们可以随意移动指针
|
|
|
|
// so long as the struct hasn't moved.
|
|
|
|
|
|
|
|
// Meanwhile, we are free to move the pointer around.
|
|
|
|
|
|
|
|
let mut still_unmoved = unmoved;
|
|
|
|
let mut still_unmoved = unmoved;
|
|
|
|
assert_eq!(still_unmoved.slice, NonNull::from(&still_unmoved.data));
|
|
|
|
assert_eq!(still_unmoved.slice, NonNull::from(&still_unmoved.data));
|
|
|
|
|
|
|
|
|
|
|
|
// Since our type doesn't implement Unpin, this will fail to compile:
|
|
|
|
// 因为我们的类型没有实现`Unpin`特征,下面这段代码将无法编译
|
|
|
|
// let mut new_unmoved = Unmovable::new("world".to_string());
|
|
|
|
// let mut new_unmoved = Unmovable::new("world".to_string());
|
|
|
|
// std::mem::swap(&mut *still_unmoved, &mut *new_unmoved);
|
|
|
|
// std::mem::swap(&mut *still_unmoved, &mut *new_unmoved);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
```
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
上面的代码也非常清晰,虽然使用了`unsafe`,其实更多的是无奈之举,跟之前的`unsafe`实现完全不可同日而语。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
总之通过`Pin`来实现,绝对值得优先考虑,代码清晰的同时逼格还挺高。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
## 玉树临风的自引用
|
|
|
|
|
|
|
|
```rust
|
|
|
|
|
|
|
|
use std::str;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
struct MyStruct<'a>{
|
|
|
|
|
|
|
|
Buf: Vec<u8>,
|
|
|
|
|
|
|
|
repr: Parsed<'a>
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
struct Parsed<'a>{
|
|
|
|
|
|
|
|
name:&'a str
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
fn main(){
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
let v = vec!(0065,0066,0067,0068,0069);
|
|
|
|
|
|
|
|
let s = str::from_utf8(&v).unwrap();
|
|
|
|
|
|
|
|
println!("{}",s);
|
|
|
|
|
|
|
|
let p = &v[1..=3];
|
|
|
|
|
|
|
|
let s1 = str::from_utf8(p).unwrap();
|
|
|
|
|
|
|
|
println!("{}",s1);
|
|
|
|
|
|
|
|
let par = Parsed{name:s1};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
let new1 = MyStruct{Buf:v,repr:par};
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
## 三方库解决引用循环
|
|
|
|
## 三方库解决引用循环
|
|
|
|
一些三方库也可以用来解决引用循环的问题,例如:
|
|
|
|
一些三方库也可以用来解决引用循环的问题,例如:
|
|
|
@ -126,6 +296,11 @@ fn main() {
|
|
|
|
|
|
|
|
|
|
|
|
不过需要注意的是,这些库需要目标值的内存地址不会改变,因此`Vec`动态数组就不适合,因为当内存空间不够时,Rust会重新分配一块空间来存放该数组,这会导致内存地址的改变。
|
|
|
|
不过需要注意的是,这些库需要目标值的内存地址不会改变,因此`Vec`动态数组就不适合,因为当内存空间不够时,Rust会重新分配一块空间来存放该数组,这会导致内存地址的改变。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
## 学习一本书:如何实现链表
|
|
|
|
|
|
|
|
|
|
|
|
## 总结
|
|
|
|
## 总结
|
|
|
|
本文深入讲解了何为引用循环以及如何使用Weak来解决,同时还结合`Rc`、`RefCell`、`Weak`等实现了两个有实战价值的例子,让大家对智能指针的使用更加融会贯通。
|
|
|
|
上面讲了这么多方法,但是我们依然无法正确的告诉你在某个场景应该使用哪个方法,这个需要你自己的判断,因为自引用实在是过于复杂。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
我们能做的就是告诉你,有这些办法可以解决自引用问题,而这些办法每个都有自己适用的范围,需要你未来去深入的挖掘和发现。
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
偷偷说一句,就算是我,遇到自引用一样挺头疼,好在这种情况真的不常见,往往是实现特定的算法和数据结构时才需要,应用代码中几乎用不到。
|