就像某种保存对值或其他内容的引用的Box
?在读取该值之前,我必须检查该值是否仍然存在,就像 Option
模式匹配时一样。
模拟示例:
struct Whatever {
thing: AliveOrNot<i32>,
}
fn main() {
let mut w = Whatever { thing: Holder::Empty };
w.thing = AliveOrNot::new(100);
match w.thing {
Empty => println!("doesn't exist"),
Full(value) => println!("{}", value),
}
}
确切的情况是我正在使用 sdl2 Font
我想将该结构的实例存储在另一个结构中。我不想做这样的事情,因为 Parent
必须与 Font
一样长:
struct Font<'a, 'b> {
aa: &'a i32,
bb: &'b i32,
}
struct Parent<'a, 'b, 'c> {
f: &'c Font<'a, 'b>
}
我想要的是Parent
能够工作,无论该字段是否仍然存在。
最佳答案
您可能对 std::rc::Weak
或 std::sync::Weak
感兴趣:
use std::rc::{Rc, Weak};
struct Whatever {
thing: Weak<i32>,
}
impl Whatever {
fn do_it(&self) {
match self.thing.upgrade() {
Some(value) => println!("{}", value),
None => println!("doesn't exist"),
}
}
}
fn its_dead_jim() -> Whatever {
let owner = Rc::new(42);
let thing = Rc::downgrade(&owner);
let whatever = Whatever { thing };
whatever.do_it();
whatever
}
fn main() {
let whatever = its_dead_jim();
whatever.do_it();
}
42
doesn't exist
使用非'static
引用在安全的Rust中没有方法可以做到这一点。 Rust 引用的一个重要点是不可能引用无效值。
您可能会泄漏内存,创建一个
&'static i32
,但如果您需要多次执行此操作,则这是不可持续的。您可以使用
不安全
代码并处理没有生命周期概念的原始指针。然后,您承担确保不会引入内存不安全的责任。
另请参阅:
- Need holistic explanation about Rust's cell and reference counted types
- Situations where Cell or RefCell is the best choice
- Is there a shared pointer with a single strong owner and multiple weak references?
- Why can't I store a value and a reference to that value in the same struct?
- How to convert a String into a &'static str
- Is there any way to return a reference to a variable created in a function?
- How to solve this rust lifetime bound issue of SDL2?
- Cannot infer an appropriate lifetime for autoref due to conflicting requirements
关于rust - 有没有办法让结构体包含可能不再有效的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60508705/