相关疑难解决方法(0)

从函数返回闭包

注意:这个问题是在Rust第一次稳定发布之前提出的.之后发生了很多变化,函数中使用的语法甚至不再有效.尽管如此,Shepmaster的答案仍然非常出色,这使得这个问题值得保留.


最后,未装箱的封闭装置着陆了,所以我正在试验它们,看看你能做些什么.

我有这个简单的功能:

fn make_adder(a: int, b: int) -> || -> int {
    || a + b
}
Run Code Online (Sandbox Code Playgroud)

但是,我收到了一个missing lifetime specifier [E0106]错误.我试图通过将返回类型更改为修复此问题||: 'static -> int,但后来又出现了另一个错误cannot infer an appropriate lifetime due to conflicting requirements.

如果我理解正确,关闭是未装箱的,所以它拥有ab.我觉得它需要一辈子似乎很奇怪.我怎样才能解决这个问题?

rust

32
推荐指数
3
解决办法
1万
查看次数

如何将对堆栈变量的引用传递给线程?

我正在编写一个WebSocket服务器,其中一个Web客户端连接到多线程计算机AI上下棋.WebSocket服务器想要将Logger对象传递给AI代码.该Logger对象将管理从AI到Web客户端的日志行.在Logger必须包含对客户端连接的参考.

我对生命周期如何与线程交互感到困惑.我用Wrapper类型参数化的结构重现了这个问题.该run_thread函数尝试解包该值并记录它.

use std::fmt::Debug;
use std::thread;

struct Wrapper<T: Debug> {
    val: T,
}

fn run_thread<T: Debug>(wrapper: Wrapper<T>) {
    let thr = thread::spawn(move || {
        println!("{:?}", wrapper.val);
    });

    thr.join();
}

fn main() {
    run_thread(Wrapper::<i32> { val: -1 });
}
Run Code Online (Sandbox Code Playgroud)

wrapper参数存在于堆栈中,并且它的生命周期不会延伸超过run_thread堆栈帧,即使该线程将在堆栈帧结束之前连接.我可以从堆栈中复制值:

use std::fmt::Debug;
use std::thread;

struct Wrapper<T: Debug + Send> {
    val: T,
}

fn run_thread<T: Debug + Send + 'static>(wrapper: Wrapper<T>) {
    let thr = thread::spawn(move || …
Run Code Online (Sandbox Code Playgroud)

rust

22
推荐指数
1
解决办法
3771
查看次数

如何在线程中使用静态生命周期?

我目前正在Rust(1.0)的生命中挣扎,特别是在通过通道传递结构时.

我将如何编译这个简单的例子:

use std::sync::mpsc::{Receiver, Sender};
use std::sync::mpsc;
use std::thread::spawn;
use std::io;
use std::io::prelude::*;

struct Message<'a> {
    text: &'a str,
}

fn main() {
    let (tx, rx): (Sender<Message>, Receiver<Message>) = mpsc::channel();

    let _handle_receive = spawn(move || {
        for message in rx.iter() {
            println!("{}", message.text);
        }
    });

    let stdin = io::stdin();
    for line in stdin.lock().lines() {
        let message = Message {
            text: &line.unwrap()[..],
        };
        tx.send(message).unwrap();
    }
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

error[E0597]: borrowed value does not live long enough
  --> src/main.rs:23:20
   |
23 |             text: …
Run Code Online (Sandbox Code Playgroud)

channel rust lifetime-scoping

8
推荐指数
1
解决办法
2239
查看次数

使用线程时终生难过

我很难编译这个:

use std::thread::{self, JoinHandle};

struct Foo<'c> {
    foo: &'c str,
}

impl<'c> Foo<'c> {
    fn use_in_another_thread<F>(self, mut cb: F) -> JoinHandle<Foo<'c>>
        where F: FnOnce(&mut Foo),
              F: Send
    {
        thread::spawn(move || {
            cb(&mut self);
            self
        })
    }
}

fn main() {}
Run Code Online (Sandbox Code Playgroud)

据我所知,生命是健全的,但我收到了错误......

error[E0477]: the type `[closure@src/main.rs:12:23: 15:10 cb:F, self:Foo<'c>]` does not fulfill the required lifetime
  --> src/main.rs:12:9
   |
12 |         thread::spawn(move || {
   |         ^^^^^^^^^^^^^
   |
   = note: type must outlive the static lifetime

error[E0495]: cannot infer an appropriate lifetime due …
Run Code Online (Sandbox Code Playgroud)

closures lifetime rust

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

在线程中使用方法时,"类型不满足所需的生命周期"

我试图在Rust中的一个线程中使用一个方法,但我收到以下错误消息

:21:10:21:23错误:类型[closure@<anon>:21:24: 23:14 tx:std::sync::mpsc::Sender<i32>, self:&MyStruct, adder:i32, a:i32] 不符合要求的生命周期:21
thread :: spawn(move || {^ ~~~~~~~~~~~~:18:9:24:10注意:在for循环扩展的扩展中注意:type必须比静态生命周期错误更长:由于先前的错误而中止

这是示例代码:

use std::thread;
use std::sync::mpsc;

struct MyStruct {
    field: i32
}

impl MyStruct {
    fn my_fn(&self, adder1: i32, adder2: i32) -> i32 {
        self.field + adder1 + adder2
    }

    fn threade_test(&self) {
        let (tx, rx) = mpsc::channel();
        let adder = 1;
        let lst_adder = vec!(2, 2, 2);

        for a in lst_adder {
            let tx = tx.clone();

            thread::spawn(move || {
                let _ = tx.send(self.my_fn(adder, a));
            }); …
Run Code Online (Sandbox Code Playgroud)

multithreading rust

5
推荐指数
1
解决办法
2265
查看次数

传递给新线程的变量的生命周期

编译此程序时遇到问题:

use std::env;
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

fn main() {
    let args: Vec<_> = env::args().skip(1).collect();

    let (tx, rx) = mpsc::channel();

    for arg in &args {
        let t = tx.clone();

        thread::spawn(move || {
            thread::sleep(Duration::from_millis(50));
            let _new_arg = arg.to_string() + "foo";
            t.send(arg);
        });
    }

    for _ in &args {
        println!("{}", rx.recv().unwrap());
    }
}
Run Code Online (Sandbox Code Playgroud)

我从命令行读取所有参数,并模拟对线程中的每个参数做一些工作.然后我打印出这项工作的结果,我使用一个频道.

error[E0597]: `args` does not live long enough
  --> src/main.rs:11:17
   |
11 |     for arg in &args {
   |                 ^^^^ does not live long enough
...
24 …
Run Code Online (Sandbox Code Playgroud)

rust

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

线程引用需要静态生存期?

虽然直觉上传递给生成的线程的引用需要具有静态生命周期,但我不清楚究竟是什么使得以下代码无法编译:

use std::sync::Arc;
use std::sync::Mutex;

struct M;

fn do_something(m : Arc<Mutex<&M>>) {
    println!("Ha, do nothing!");
}

fn main() {
    let a = M;
    {
        let c : Arc<Mutex<&M>> = Arc::new(Mutex::new(&a));
        for i in 0..2 {
            let c_clone = c.clone();
            ::std::thread::spawn(move || do_something(c_clone));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

编译这个小程序会出现以下错误:

$ rustc -o test test.rs
test.rs:13:55: 13:56 error: `a` does not live long enough
test.rs:13         let c : Arc<Mutex<&M>> = Arc::new(Mutex::new(&a));
                                                             ^
note: reference must be valid for the static lifetime...
Run Code Online (Sandbox Code Playgroud)

在我看来,变量a将会超出现实 …

multithreading lifetime rust

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

无法在生成的线程中调用函数,因为它"无法满足所需的生命周期"

我可以运行这段代码

fn testf(host: &str) {}

fn start(host: &str) {
    testf(host);
    testf(host);
}
Run Code Online (Sandbox Code Playgroud)

但出于某种原因,我无法运行这个:

fn testf(host: &str) {}

fn start(host: &str) {
    thread::spawn(move || testf(host));
    thread::spawn(move || testf(host));
}
Run Code Online (Sandbox Code Playgroud)

因为以下错误

src/server.rs:30:5: 30:18 error: the type `[closure@src/server.rs:30:19: 30:38 host:&str]` does not fulfill the required lifetime
src/server.rs:30     thread::spawn(move || testf(host));
                     ^~~~~~~~~~~~~
note: type must outlive the static lifetime
error: aborting due to previous error
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下,它有什么问题以及如何解决它?

multithreading closures lifetime rust

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