首先让我们做一个简单的工作示例,我们可以实际编译:
trait Query {
fn get_data<'backend>(&self, backend: &'backend Backend) -> Result<'backend>;
}
struct Result<'data> {
data: &'data str,
}
struct Backend {
database_data: String,
}
struct SomeQuery {
length_filter: usize,
}
impl Query for SomeQuery {
fn get_data<'backend>(&self, backend: &'backend Backend) -> Result<'backend> {
Result {
// we use SomeQuery here, but it's not in the data
data: &backend.database_data[..self.length_filter],
}
}
}
impl Backend {
fn get_paginated_entities<'backend>(
&'backend self,
query: &'backend SomeQuery,
) -> Result<'backend> {
query.get_data(self)
}
}
fn get_some_entities<'backend>(
length_filter: usize,
backend: &'backend Backend,
) -> Result<'backend> {
backend.get_paginated_entities(&SomeQuery { length_filter })
}
希望现在更容易找到问题;Rust认为数据与查询具有相同的生存期,因为我们
告诉
是的!
fn get_paginated_entities<'backend>(
// the returned data is referenced from the backend,
// so we specify a lifetime that Result lives as long
// as backend does
&'backend self,
// but we told Rust here that query also has a lifetime
// of 'backend, so the query also has to live as long as
// the return value does
query: &'backend SomeQuery,
) -> Result<'backend> {
query.get_data(self)
}
在这里,我们可以使用多个生存期来表示返回值的生存期与查询生存期没有任何关系(在本例中,我们实际上不需要它,但您可以在代码中使用它)。
fn get_paginated_entities<'backend, 'query>(
&'backend self,
// now the return data isn't linked to query's lifetime
query: &'query SomeQuery,
) -> Result<'backend> {
query.get_data(self)
}
这很好,因为
get_data
还规定
query
的寿命与
Result
.
fn get_data<'backend>(&self, backend: &'backend Backend) -> Result<'backend>;
编辑:这里的问题也与
async
; 因为我们不知道代码何时运行,所以数据必须是
'static
.我们可以用
Rc
而不是普通的参考。
钢筋混凝土
实际上,它有一个静态的生命周期,因为它可以永远浮动,直到不再有对它的引用。