标签: rust-lifetimes

令人困惑的借用检查器消息:“终生不匹配”

我最近遇到了一条我从未见过的借用检查器消息,我试图理解它。这是重现它的代码(简化的,现实生活中的例子更复杂)-操场

fn foo(v1: &mut Vec<u8>, v2: &mut Vec<u8>, which: bool) {
    let dest = if which { &mut v1 } else { &mut v2 };
    dest.push(1);
}
Run Code Online (Sandbox Code Playgroud)

它无法编译并出现以下错误:

error[E0623]: lifetime mismatch
 --> src/main.rs:2:44
  |
1 | fn foo(v1: &mut Vec<u8>, v2: &mut Vec<u8>, which: bool) {
  |            ------------      ------------ these two types are declared with different lifetimes...
2 |     let dest = if which { &mut v1 } else { &mut v2 };
  |                                            ^^^^^^^ ...but data from …
Run Code Online (Sandbox Code Playgroud)

rust borrow-checker rust-lifetimes

6
推荐指数
1
解决办法
172
查看次数

Rust 中的“一种类型比另一种更通用”错误,而类型相同

我有以下代码

use std::future::Future;
fn main() {
    handle(Test::my_func);
}

fn handle<Fut>(fun: for<'r> fn(&'r mut Test) -> Fut) -> bool
where
    Fut: Future<Output = ()>,
{
    true
}

struct Test {}

impl Test {
    pub async fn my_func<'r>(&'r mut self) -> () {
        ()
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,您可以在Rust Playground上在线运行它。

出现以下错误:

error[E0308]: mismatched types
  --> src/main.rs:4:12
   |
4  |     handle(Test::my_func);
   |            ^^^^^^^^^^^^^ one type is more general than the other
...
17 |     pub async fn my_func<'r>(&'r mut self) -> () { …
Run Code Online (Sandbox Code Playgroud)

rust lifetime-scoping rust-async-std rust-lifetimes rust-futures

4
推荐指数
1
解决办法
118
查看次数