Skip to content

Allow lifetime parameters on generic types #8973

Closed
@sfackler

Description

@sfackler

TL;DR

It'd be nice if something like this were possible:

trait Foo {}

trait Bar<F: Foo> {
    fn bar<'a>(&'a self) -> F<'a>;
}

This'd probably require some new syntax to limit F to Foos with lifetime parameters. Potentially related to #5922.

Use Case

In https://github.com/sfackler/rust-postgres, the PostgresConnection and PostgresTransaction types can both prepare statements. However, PostgresConnection.prepare and PostgresTransaction.prepare return different implementations of the PostgresStatement trait. Both implementations of PostgresStatement contain borrowed pointers to their parent PostgresConnection and the lifetime of a statement is semantically tied to a connection in any case. I'd like to have a trait to unify this functionality. It'd look something like

pub trait PostgresPreparer<S: PostgresStatement> {
    fn try_prepare<'a>(&'a self, query: &str) -> Result<S<'a>, PostgresDbError>;

    fn prepare<'a>(&'a self, query: &str) -> S<'a> {
        match try_prepare(query) {
            Ok(stmt) => stmt,
            Err(err) => fail2!("Error preparing statement: {}", err.to_str())
        }
    }

    fn try_update(&self, query: &str, params: &[&ToSql]) -> Result<uint, PostgresDbError> {
        do self.try_prepare(query).chain |stmt| {
            stmt.try_update(params)
        }
    }

    fn update(&self, query: &str, params: &[&ToSql]) -> uint {
        match self.try_update(query, params) {
            Ok(updated) => updated,
            Err(err) => fail2!("Error executing query: {}", err.to_str())
        }
    }

}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lifetimesArea: Lifetimes / regions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions