小编Chr*_*ris的帖子

在迭代时修改结构是否有优雅的解决方案?

我正在尝试构建迭代它们时更改的点向量:

struct Point {
    x: i16,
    y: i16,
}

fn main() {
    let mut points: Vec<Point> = vec![];
    // unsure if point is mutable
    points.push(Point { x: 10, y: 10 });
    // thus trying it explicitly
    let mut p1 = Point { x: 20, y: 20 };
    points.push(p1);

    for i in points.iter() {
        println!("{}", i.x);
        i.x = i.x + 10;
    }
}
Run Code Online (Sandbox Code Playgroud)

编译时,我收到错误:

error[E0594]: cannot assign to immutable field `i.x`
  --> src/main.rs:16:9
   |
16 |         i.x = i.x + 10; …
Run Code Online (Sandbox Code Playgroud)

rust

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

通过什么论点以及如何找出它的类型?

我从mio网页开始使用EventLoop的示例并添加了main函数:

extern crate mio;

use std::thread;
use mio::{EventLoop, Handler};

struct MyHandler;

impl Handler for MyHandler {
    type Timeout = ();
    type Message = u32;

    fn notify(&mut self, event_loop: &mut EventLoop<MyHandler>, msg: u32) {
        assert_eq!(msg, 123);
        event_loop.shutdown();
    }
}

fn main() {
    let mut event_loop = EventLoop::new().unwrap();
    let sender = event_loop.channel();

    // Send the notification from another thread
    thread::spawn(move || {
        let _ = sender.send(123);
    });

    let _ = event_loop.run(&mut MyHandler);
}
Run Code Online (Sandbox Code Playgroud)

然后我有了将发送线程移动到单独的函数"foo"并开始想知道传递什么类型的想法:

extern crate mio;

use std::thread;
use …
Run Code Online (Sandbox Code Playgroud)

rust

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

标签 统计

rust ×2