相关疑难解决方法(0)

无法借用“Arc”中的可变数据

我不知道下一步该做什么。看起来我误解了一些东西,或者我可能没有学到一些关键的话题。

use std::sync::Arc;

use reqwest::{Error, Response}; // 0.11.4
use tokio::sync::mpsc::{self, Receiver, Sender}; // 1.9.0

pub struct Task {
    pub id: u32,
    pub url: String,
}
pub enum Message {
    Failure(Task, Error),
    Success(Task, Response),
}

struct State {
    client: reqwest::Client,
    res_tx: Sender<Message>,
    res_rx: Receiver<Message>,
}

pub struct Proxy {
    state: Arc<State>,
    max_rps: u16,
    max_pending: u16,
    id: u32,
    parent_tx: Sender<String>,
}

async fn send_msg<T>(tx: &Sender<T>, msg: T) {
    match tx.send(msg).await {
        Err(error) => {
            eprintln!("{}", error)
        }
        _ => (),
    };
} …
Run Code Online (Sandbox Code Playgroud)

rust rust-tokio

18
推荐指数
2
解决办法
3万
查看次数

如何从Arc <Mutex <T >>取得T的所有权?

我想从一个受a保护的函数返回一个值Mutex,但是无法理解如何正确地执行它.此代码不起作用:

use std::sync::{Arc, Mutex};

fn func() -> Result<(), String> {
    let result_my = Arc::new(Mutex::new(Ok(())));
    let result_his = result_my.clone();

    let t = std::thread::spawn(move || {
        let mut result = result_his.lock().unwrap();
        *result = Err("something failed".to_string());
    });

    t.join().expect("Unable to join thread");

    let guard = result_my.lock().unwrap();
    *guard
}

fn main() {
    println!("func() -> {:?}", func());
}
Run Code Online (Sandbox Code Playgroud)

操场

编译器抱怨:

error[E0507]: cannot move out of borrowed content
  --> src/main.rs:16:5
   |
16 |     *guard
   |     ^^^^^^ cannot move out of borrowed content
Run Code Online (Sandbox Code Playgroud)

rust

12
推荐指数
2
解决办法
2942
查看次数

终身麻烦在线程之间共享引用

我有一个启动工作线程的线程,所有线程都应该永远存在.每个工作线程都维护着自己的Sockets 列表.

有些操作要求我遍历当前活动的所有套接字,但是我在尝试创建包含指向另一个列表所拥有的套接字的指针的套接字的主列表时遇到了麻烦.

use std::{str, thread};
use std::thread::JoinHandle;
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::ops::DerefMut;
use std::sync::mpsc::{channel, Sender, Receiver, TryRecvError};
use self::socketlist::SocketList;
use self::mastersocketlist::MasterSocketList;

pub struct Socket {
    user: String,
    stream: TcpStream,
}

mod socketlist {
    use self::SocketList::{Node, End};
    use super::Socket;

    pub enum SocketList {
        Node(Socket, Box<SocketList>),
        End,
    }

    impl SocketList {
        pub fn new() -> SocketList {
            End
        }

        pub fn add(self, socket: Socket) -> SocketList {
            Node(socket, Box::new(self))
        }

        pub fn newest<'a>(&'a …
Run Code Online (Sandbox Code Playgroud)

lifetime rust

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

如何使包含 Arc 的结构字段可写?

我有一个必须以原始指针形式检索的结构。

pub struct BufferData {
    /// Memory map for pixel data
    pub map: Arc<Box<memmap::MmapMut>>,
    pub otherdata: i32,
}
Run Code Online (Sandbox Code Playgroud)

我需要写入它的map字段,所以我将原始指针解引用到结构中,然后尝试写入它的数据字段。但是,我收到以下错误。

pub struct BufferData {
    /// Memory map for pixel data
    pub map: Arc<Box<memmap::MmapMut>>,
    pub otherdata: i32,
}
Run Code Online (Sandbox Code Playgroud)

如何使map字段可变和可写?

使用以下代码可重现该错误:

extern crate memmap;

use std::fs::File;
use std::sync::Arc;
use std::boxed::Box;
use std::ops::Deref;

pub struct BufferData {
    /// Memory map for pixel data
    pub map: Arc<Box<memmap::MmapMut>>,
    pub otherdata: i32,
}

fn main() -> () {
    // Somewhere on other module …
Run Code Online (Sandbox Code Playgroud)

immutability dereference rust raw-pointer

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

在线程之间可变地共享i32

我是Rust和线程的新手,我正在尝试打印一个数字,同时在另一个线程中添加它.我怎么能做到这一点?

use std::thread;
use std::time::Duration;

fn main() {
    let mut num = 5;
    thread::spawn(move || {
        loop {
            num += 1;
            thread::sleep(Duration::from_secs(10));
        }
    });
    output(num);
}

fn output(num: i32) {
    loop {
        println!("{:?}", num);
        thread::sleep(Duration::from_secs(5));
    }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码不起作用:它总是打印5,好像数字永远不会增加.

multithreading rust

2
推荐指数
2
解决办法
651
查看次数

Send 只能针对 struct/enum 类型实现,而不能针对 Trait 实现

我很难实现Send某个特质。完整代码在操场上

我有一个Storage特点:

pub trait Storage {
    fn get_value(&self, key: &str) -> Result<Vec<u8>, Error>;
    fn put_value(&mut self, key: &str, value: &[u8]) -> Result<(), Error>;
    fn key_exists(&self, key: &str) -> bool;
    fn delete_key(&mut self, key: &str) -> Result<(), Error>;
}
Run Code Online (Sandbox Code Playgroud)

它是Consistency结构的一部分:

pub struct Consistency<'a> {
    storage: &'a mut Storage,
}
Run Code Online (Sandbox Code Playgroud)

我已经实现了一个MemoryStorage结构:

#[derive(Debug)]
struct MemoryStorage {
    data: HashMap<String, Vec<u8>>,
}

impl Storage for MemoryStorage {
    fn get_value(&self, key: &str) -> Result<Vec<u8>, Error> { …
Run Code Online (Sandbox Code Playgroud)

multithreading rust

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

在Rc封装的对象中调用可变方法的标准方法是什么?

在下面的代码中,我试图通过调用其方法之一来更改已计数对象的值:

use std::rc::Rc;

fn main() {
    let mut x = Rc::new(Thing { num: 50 });
    x.what_to_do_to_get_mut_thing().change_num(19); //what do i do here
}

pub struct Thing {
    pub num: u32,
}

impl Thing {
    pub fn change_num(&mut self, newnum: u32) {
        self.num = newnum;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在使用该get_mut函数来实现此目的,但是我不知道这是否是实现此目标的标准方法。

if let Some(val) = Rc::get_mut(&mut x) {
    val.change_num(19);
}
Run Code Online (Sandbox Code Playgroud)

rust

0
推荐指数
2
解决办法
629
查看次数