[英]How to indicate that the lifetime of an async function's return value is the same as a parameter?
[英]Lifetime of return value not directly related to parameter lifetime
我是 rust 的新手,並且無法為我正在嘗試做的事情找出正確的設計模式。 在我的程序中,有 Position 個結構,它們引用它們“屬於”的單個坐標系。 據我所知, rust 因此必須能夠保證coordinate_system
參考比Position
。 到目前為止,一切都很好。
問題出在 function 中,例如transform_to_parent
,我想在其中創建一個新的Position
,它取決於它后來引用的確切coordinate_system
的生命周期,而不是它訪問坐標系所通過的self
參數的生命周期。 這似乎是生命周期說明符唯一允許的事情。
如果我在下面的代碼中添加一個生命周期說明符,它會編譯,但是當我讓我從 scope 中轉換出來的舊 Position 消失時,可以理解地抱怨。
pub struct Position<'a> {
// Position data omitted
coordinate_system: &'a CoordinateSystem<'a>,
}
impl<'a> Position<'a> {
fn transform_to_parent<'b>(self: &'b Self) -> Option<Position<'b>> {
Some(Position {
coordinate_system: self.coordinate_system.origin?.coordinate_system
})
}
}
pub struct CoordinateSystem<'a> {
origin: Option<&'a Position<'a>>,
}
// Test case
fn main() {
// child_system is the child coordinate system of root_system, and has its origin at child_origin
let root_system = CoordinateSystem { origin: None };
let child_origin = Position { coordinate_system: &root_system };
let child_system = CoordinateSystem { origin: Some(&child_origin) };
let mut p2 = Position { coordinate_system: &child_system };
{
let p1 = Position { coordinate_system: &child_system };
if let Some(x) = p1.transform_to_parent() { // Error: "borrowed value does not live long enough"
p2 = x;
}
}
// No-op, just pretend to use p2 again, after p1 has gone out of scope
p2;
}
Rust 是否可以將 function 結果的生命周期綁定到self.coordinate_system.get_origin()?.coordinate_system
(即父坐標系)的生命周期,而不是self
? 這樣的東西有正確的設計模式嗎?
我假設引用計數系統會起作用,但我認為那將是糟糕的設計,因為坐標系有明確的所有權,而且生命周期信息應該可以以某種方式推導出來。
只需使用'a
一生”:
impl<'a> Position<'a> {
fn transform_to_parent(&self) -> Option<Position<'a>> {
Some(Position {
coordinate_system: self.coordinate_system.origin?.coordinate_system
})
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.