【问题标题】:How do implement a named lifetime for a type inside of a trait that doesn't take a lifetime parameter?如何为不采用生命周期参数的特征内的类型实现命名生命周期?
【发布时间】:2020-08-09 17:23:27
【问题描述】:

我正在尝试为 SQL Server 实现 r2d2::ManageConnection 特征。我遇到的问题是我想用于我的实现的连接结构需要一个生命周期参数,但我不知道如何指定生命周期。

添加一个命名的生命周期会产生预期的错误。

 impl r2d2::ManageConnection for SQL_Server_Manager{
    type Connection = odbc::Connection<'a, AutocommitOn>;

type Connection = odbc::Connection<'a, AutocommitOn>;
                                   ^^ undeclared lifetime

尝试使用未命名的生命周期也会引发错误

type Connection = odbc::Connection<'_, AutocommitOn>;
                                    ^^ expected named lifetime parameter

并且尝试将命名的生命周期参数添加到特征会引发错误

impl<'a> r2d2::ManageConnection<'a> for SQL_Server_Manager{
                                ^^ unexpected lifetime argument

在不采用生命周期参数的 Trait 实现中使用需要命名生命周期参数的类型的正确方法是什么?

【问题讨论】:

    标签: rust


    【解决方案1】:

    如果您在实现者类型中设置生命周期(在您的情况下为SQL_Server_Manager),它就会编译。必须在里面放一个PhantomData 才能使用这个生命周期并避免另一个编译错误。

    Playground

    struct Foo<'a> {
        val: &'a str,
    }
    
    #[derive(Default)]
    struct Bar<'a> {
        pd: std::marker::PhantomData<&'a u32>,
    }
    
    trait Trait {
        type Connection;
        fn fun(&self, con: Self::Connection);
    }
    
    impl<'a> Trait for Bar<'a> {
        type Connection = Foo<'a>;
        fn fun(&self, con: Self::Connection) {
            println!("Implemented {}", con.val);
        }
    }
    
    fn main() {
        let b = Bar::default();
        b.fun(Foo{ val:"FOO" }); // Implemented FOO
    }
    

    【讨论】:

    • 谢谢! PhantomData 类型实现是我卡住的地方。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 2019-12-18
    • 2022-08-22
    相关资源
    最近更新 更多