SuperAPI AI Directory

rust-lifetime-complex

Coding & development

View repository

Updated 10-16 08:49

About this skill

Advanced Lifetimes and the Type System

Core Problem

Why does this type conversion simply not compile?

The boundaries of the type system are often unexpected.


HRTB + dyn Trait Object Conflict

Problem Code

// ❌ HRTB 不能装进 dyn trait object
pub type ConnFn<T> =
    dyn for<'c> FnOnce(&'c mut PgConnection) -> BoxFuture<'c, T> + Send;

let f = Box::new(move |conn: &mut PgConnection| -> BoxFuture<'_, i64> { Box::pin(async { Ok(42) }) }) as Box<ConnFn>; // ❌ "one type is more general than the other"


### 原因

- 闭包有**具体生命周期** `'_`
- `ConnFn<T>` 要求**任意生命周期** `for<'c>`
- 具体不能自动变成通用

### 解决:把 HRTB 留在函数边界

```rust
// ✅ HRTB 只在调用点使用泛型
impl Db {
    pub async fn with_conn<F, T, Fut>(&self, f: F) -> Result<T, DbError>
    where
        F: for<'c> FnOnce(&'c mut PgConnection) -> Fut + Send,
        Fut: Future<Output = Result<T, DbError>> + Send,
    {
        let mut conn = self.pool.acquire().await?;
        f(&mut conn).await
    }
}

Usage

db.with_conn(|conn| async move {
    // 这里 'c 由调用时确定,不需要 dyn
    sqlx::query("...").fetch_all(conn).await
}).await

GAT + dyn Trait Object

Problem Code

// ❌ GAT 不能和 dyn Trait 一起用
trait ReportRepo: Send + Sync {
    type Row<'r>: RowView<'r>;  // ❌ GAT
}

let repo: Arc<dyn ReportRepo> = ...;  // ❌ 编译错误

Error Message

error[E0038]: the trait cannot be made into an object
because associated type `Row` has generic parameters

Reason

  • dyn ReportRepo requires a uniform size
  • Row<'r> for different 'r has different sizes
  • Object safety rules prohibit

Solution: Layered Architecture

// 内部:GAT + 借用(高性能)
trait InternalRepo {
    type Row<'r>: RowView<'r>;
    async fn query<'c>(&'c self) -> Vec<Self::Row<'c>>;
}

// 外部:owned DTO(兼容 GraphQL)
pub trait PublicRepo: Send + Sync {
    async fn query(&self) -> Vec<ReportDto>;  // owned
}

// 适配层
impl PublicRepo for PgRepo {
    async fn query(&self) -> Vec<ReportDto> {
        let rows = self.internal.query().await;  // 借用内部
        rows.into_iter().map(|r| r.to_dto()).collect()
    }
}

Architecture Diagram

GraphQL Layer (需要 'static)
         ↓
    PublicRepo Trait (owned)
         ↓
    Adapter (转换 borrowed → owned)
         ↓
    InternalRepo Trait (GAT, borrowed)
         ↓
    DB Implementation

'static Requirement Conflict

Scenario

// async-graphql 要求 schema 是 'static
// 但 repo 方法返回借用数据
async fn resolve(&self) -> Result<&'r Row<'r>> {
    // ❌ 'r 不能 outlive 'static
}

Solution: owned data

// 不要在 API 层暴露借用
async fn resolve(&self) -> Result<ReportDto> {
    let row = self.repo.query().await?;  // owned
    Ok(row.to_dto())
}

When to Make an Exception

  • Only for very short-lived borrows (such as within a single function call)
  • Full control over the lifetimes of owners and borrows
  • The performance gain is significant and irreplaceable

Common Conflict Patterns

Pattern Cause of Conflict Solution
HRTB → dyn Concrete vs generic Replace dyn with a generic function
GAT → dyn Non-fixed size Layered design
'static + borrow Lifetime contradiction owned data
async + lifetime Coroutine holds state drop borrow or owned
closure capture + Send Lifetime issue Clone or 'static

When to Give Up on Borrowing

Performance vs Maintainability

// 性能收益 vs 复杂性
fn should_borrow() -> bool {
    // 大数据结构 → 借用
    // 高频访问 → 借用
    // 生命周期简单 → 借用
    
    // 复杂生命周期 → owned
    // API 边界 → owned
    // 异步上下文 → owned
}

Rules of Thumb

  1. API layer: default to owned
  2. Internal implementation: borrow as needed
  3. Performance hotspots: consider borrowing
  4. When complexity is high: fall back to owned

Debugging Techniques

Compiler Errors

Error Meaning
"one type is more general" Attempting to convert concrete to generic
"lifetime may not live long enough" Borrow out of scope
"cannot be made into an object" GAT + dyn incompatible
"does not live long enough" Borrow released early

Methods

  1. Minimize: write the smallest reproducible code
  2. Annotate lifetimes: explicitly write out all lifetimes
  3. Simplify step by step: remove abstractions and face the problem directly
  4. Accept reality: not all designs can compile