【问题标题】:Sorting out different lifetimes on Self and a method整理 Self 的不同生命周期和方法
【发布时间】:2014-07-20 17:34:11
【问题描述】:

我昨晚发布了一个类似的问题 (Rust lifetime error expected concrete lifetime but found bound lifetime),但现在仍然不知道如何将其应用于此案例。再一次,下面是一个简化的例子:

struct Ref;

struct Container<'a> {
  r : &'a Ref
}

struct ContainerB<'a> {
  c : Container<'a>
}

trait ToC {
  fn from_c<'a>(r : &'a Ref, c : Container<'a>) -> Self;
}

impl<'b> ToC for ContainerB<'b> {
  fn from_c<'a>(r : &'a Ref, c : Container<'a>) -> ContainerB<'a> {
    ContainerB{c:c}
  }
}

带有错误信息:

test.rs:16:3: 18:4 error: method `from_c` has an incompatible type for trait: expected concrete lifetime, but found bound lifetime parameter 'a
test.rs:16   fn from_c<'a>(r : &'a Ref, c : Container<'a>) -> ContainerB<'a> {
test.rs:17     ContainerB{c:c}
test.rs:18   }
test.rs:16:67: 18:4 note: expected concrete lifetime is the lifetime 'b as defined on the block at 16:66
test.rs:16   fn from_c<'a>(r : &'a Ref, c : Container<'a>) -> ContainerB<'a> {
test.rs:17     ContainerB{c:c}
test.rs:18   }
error: aborting due to previous error

我认为需要发生的是我需要某种方式来等同/子类型生命周期'a 和生命周期'b。与前面的示例不同,没有要使用的 &amp;self。我猜我可以通过向我的 trait (trait ToC&lt;'a&gt; ...) 添加生命周期类型参数来做到这一点,但我不希望这样做,因为它会在我想使用 trait 作为类型绑定的任何地方添加额外的 &lt;'a&gt;

如果有人好奇(AKA 可以忽略这一点)这可能会出现在哪里,我会在库中使用它来在 rust 和 python 类型之间进行转换。特征是here。一切正常,但我正在尝试围绕 PyObject 类型(例如 numpy ndarray)实现一个包装器,并能够使用它在 PyObject 之间进行转换。

再次感谢!

【问题讨论】:

    标签: rust traits lifetime


    【解决方案1】:

    这归结为与您上一个问题大致相同的问题。

    Self 指的是您正在为其实现特征的类型。在这种情况下,它是ContainerB&lt;'b&gt;,所以它不一样的整个事情都适用;这次这次也没有什么可以将'b'a 绑定在一起;编译器必须并且必须假定生命周期可能是不相交的。 (这与保证'b ≥ 'a&amp;'a ContainerB&lt;'b&gt; 不同。)

    一旦您使用了在方法上定义的生命周期,就不可能将其与 Self 上的生命周期联系起来。可能最好的解决方案是将生命周期参数从方法转移到特征上:

    trait ToC<'a> {
        fn from_c(r: &'a Ref, c: Container<'a>) -> Self;
    }
    
    impl<'a> ToC<'a> for ContainerB<'a> {
        fn from_c(r: &'a Ref, c: Container<'a>) -> ContainerB<'a> {
            ContainerB { c: c }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多