Cor*_*onA 2 generics clone traits rust trait-objects
我正在编写一个带有边和节点的图实现。该图应同时访问,因此我选择将 Edges 和 Nodes 构建为Arc<Mutex<dyn Edge>>and Arc<RwLock<dyn Node>>。
不幸的是,我在连接节点/边时遇到编译错误the parameter type 'T' may not live long enough( Playground )。
pub trait Node {
fn connect(&mut self, edge: EdgeRef);
}
pub type NodeRef = Arc<RwLock<dyn Node>>;
pub trait Edge {
fn connect(&mut self, node: NodeRef);
}
pub type EdgeRef = Arc<Mutex<dyn Edge>>;
impl<T> Node for Arc<RwLock<T>>
where
T: Node,
{
fn connect(&mut self, edge_ref: EdgeRef) {
let mut node = self.write().unwrap();
let mut edge = edge_ref.lock().unwrap();
let self_clone = self.clone() as NodeRef; // the parameter type `T` may not live long enough
edge.connect(self_clone);
node.connect(edge_ref.clone());
}
}
Run Code Online (Sandbox Code Playgroud)
问题是:Arc<RwLock<T>>应该不是引用,所以应该没有生命周期。将其转换为Arc<RwLock<dyn Node>>也不会引入生命周期。
有人可以解释这个编译器错误吗?这个问题与每个参数类型(例如Type<T>)有关还是仅与Arc<RwLock<T>>?
编译错误解释了如何解决问题:
error[E0310]: the parameter type `T` may not live long enough
--> src/lib.rs:22:22
|
15 | impl<T> Node for Arc<RwLock<T>>
| - help: consider adding an explicit lifetime bound...: `T: 'static`
...
22 | let self_clone = self.clone() as NodeRef;
| ^^^^^^^^^^^^
|
note: ...so that the type `T` will meet its required lifetime bounds
--> src/lib.rs:22:22
|
22 | let self_clone = self.clone() as NodeRef;
| ^^^^^^^^^^^^
error: aborting due to previous error
For more information about this error, try `rustc --explain E0310`.
Run Code Online (Sandbox Code Playgroud)
添加+ 'static到您T的边界确实可以修复错误:
use std::sync::{Arc, Mutex, RwLock};
pub trait Node {
fn connect(&mut self, edge: EdgeRef);
}
pub type NodeRef = Arc<RwLock<dyn Node>>;
pub trait Edge {
fn connect(&mut self, node: NodeRef);
}
pub type EdgeRef = Arc<Mutex<dyn Edge>>;
impl<T> Node for Arc<RwLock<T>>
where
T: Node + 'static, // added "+ 'static" here
{
fn connect(&mut self, edge_ref: EdgeRef) {
let mut node = self.write().unwrap();
let mut edge = edge_ref.lock().unwrap();
let self_clone = self.clone() as NodeRef;
edge.connect(self_clone);
node.connect(edge_ref.clone());
}
}
Run Code Online (Sandbox Code Playgroud)
但是,当我的 T 永远不会成为参考时,为什么我需要终身绑定?你问。好吧,Rust 编译器还不知道, aT可以是任何类型,包括引用。表示的类型集T包括&T和表示的类型集&mut T。这两个&T和&mut T是的子集T。这就是为什么您必须将生命周期绑定到T,这是您与编译器沟通的方式,您T将只拥有类型或静态引用。
更多关于“静态生命周期”
'static是生命周期的误导性名称,因为它使大多数人认为'static类型必须在程序的整个持续时间内都存在并且不能动态分配或删除。这些在现实中都不是真的:'static类型可以动态分配,也可以删除。什么'static真正在实践中意味着“你可以放心地持有这种类型的无止境”。所有“拥有的类型”都喜欢String和Vec都是'static。这是一个 Rust 程序,我希望它可以说明这一点:
use rand::prelude::*; // 0.7.3
// this function takes 'static types and drops them
// no compiler errors because 'static types can be dynamically allocated and dropped
fn is_static<T: 'static>(t: T) {
std::mem::drop(t)
}
fn main() {
let string = String::from("string"); // dynamically allocated string
is_static(string); // compiles just fine
let mut strings: Vec<String> = Vec::new();
let mut loops = 10;
while loops > 0 {
if rand::random() {
strings.push(format!("randomly dynamically allocated string on loop {}", loops));
}
loops -= 1;
}
// all the strings are 'static
for string in strings {
is_static(string); // compiles no problem
}
}
Run Code Online (Sandbox Code Playgroud)
更多关于生命周期省略和默认特征对象生命周期
您可以定义NodeRef并EdgeRef为这样的:
pub type NodeRef = Arc<RwLock<dyn Node>>;
pub type EdgeRef = Arc<Mutex<dyn Edge>>;
Run Code Online (Sandbox Code Playgroud)
然而,Rust 编译器会这样解释:
pub type NodeRef = Arc<RwLock<dyn Node + 'static>>;
pub type EdgeRef = Arc<Mutex<dyn Edge + 'static>>;
Run Code Online (Sandbox Code Playgroud)
所以当你想投射 some Arc<RwLock<T>>to NodeRefthenT必须受到限制,Node + 'static因为NodeRef也有这些界限,即Arc<RwLock<dyn Node + 'static>>. Rust 中的所有 trait 对象都有生命周期,但你通常不会编写它们,因为 Rust 会为你推断它们。如果您想了解更多信息,Rust Reference 对生命周期省略和默认特征对象生命周期有详尽的解释。
您可以'static通过使您的类型别名泛型来缓解要求'a:
pub type NodeRef<'a> = Arc<RwLock<dyn Node + 'a>>;
pub type EdgeRef<'a> = Arc<Mutex<dyn Edge + 'a>>;
Run Code Online (Sandbox Code Playgroud)
但是,这将大大增加您的代码的复杂性,我很确定您想坚持下去,'static因为它已经支持您正在尝试做的事情。
| 归档时间: |
|
| 查看次数: |
422 次 |
| 最近记录: |