相关疑难解决方法(0)

锈蚀寿命误差预期具体寿命但发现约束寿命

我在使用结构的生命周期参数时遇到问题.我不是100%肯定如何描述问题,但我创建了一个显示我的编译时错误的简单案例.

struct Ref;

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

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

trait ToC {
  fn to_c<'a>(&self, r : &'a Ref) -> Container<'a>;
}

impl<'a> ToC for ContainerB<'a> {
  fn to_c(&self, r : &'a Ref) -> Container<'a> {
    self.c
  }
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是

test.rs:16:3: 18:4 error: method `to_c` has an incompatible type for trait: expected concrete lifetime, but found bound lifetime parameter 'a
test.rs:16   fn to_c(&self, r : &'a Ref) -> Container<'a> {
test.rs:17     self.c …
Run Code Online (Sandbox Code Playgroud)

reference lifetime rust

9
推荐指数
1
解决办法
2778
查看次数

将自我的生命周期与方法中的参考联系起来

我有这段代码:

#[derive(Debug)]
struct Foo<'a> {
    x: &'a i32,
}

impl<'a> Foo<'a> {
    fn set(&mut self, r: &'a i32) {
        self.x = r;
    }
}

fn main() {
    let v = 5;
    let w = 7;
    let mut f = Foo { x: &v };

    println!("f is {:?}", f);

    f.set(&w);

    println!("now f is {:?}", f);
}
Run Code Online (Sandbox Code Playgroud)

我的理解是,在第一次借用值时v,'astruct声明中的泛型生命周期参数将填充值的生命周期v.这意味着生成的Foo对象的'a寿命不得超过此生命周期,或者v必须至少与Foo对象一样长.

在对方法的调用中set,impl使用块上的生命周期参数,并在方法签名中w填充值的生命周期'a …

rust

7
推荐指数
1
解决办法
649
查看次数

在impl块或方法上指定特征绑定是否更好?

假设我想创建一些包含其他泛型类型的类型,如下所示:

struct MyWrapper<T> {
    pub inner: T,
}
Run Code Online (Sandbox Code Playgroud)

现在我希望我的类型有一个方法,如果内部类型满足特定的绑定.例如:我想打印它(在这个例子中没有使用fmt特征来简化).为此,我有两种可能性:向impl方法本身添加绑定.

方法绑定

impl<T> MyWrapper<T> {
    pub fn print_inner(&self) where T: std::fmt::Display {
        println!("[[ {} ]]", self.inner);
    }
}
Run Code Online (Sandbox Code Playgroud)

MyWrapper<()>我得到一个调用此函数时:

error[E0277]: `()` doesn't implement `std::fmt::Display`
  --> src/main.rs:20:7
   |
20 |     w.print_inner();
   |       ^^^^^^^^^^^ `()` cannot be formatted with the default formatter; try using `:?` instead if you are using a format string
   |
   = help: the trait `std::fmt::Display` is not implemented for `()`
Run Code Online (Sandbox Code Playgroud)

Impl Bound

impl<T: std::fmt::Display> …
Run Code Online (Sandbox Code Playgroud)

traits rust

7
推荐指数
1
解决办法
1357
查看次数

标签 统计

rust ×3

lifetime ×1

reference ×1

traits ×1