Не может выйти из «Дуги»

#rust #actix-web #rust-actix

Вопрос:

У меня есть структура под названием маршрутизация со следующими методами.

 #[derive(Clone)]
pub struct Routing {
    get_routes: Node<PyFunction>,
    post_routes: Node<PyFunction>,
    put_routes: Node<PyFunction>,
    delete_routes: Node<PyFunction>,
    patch_routes: Node<PyFunction>,
    head_routes: Node<PyFunction>,
    options_routes: Node<PyFunction>,
    connect_routes: Node<PyFunction>,
    trace_routes: Node<PyFunction>,
}

impl Routing {
    pub fn new(router: amp;Router) -> Routing {
        let get_routes = Router::protocol_to_tree(amp;router.get_routes);
        let post_routes = Router::protocol_to_tree(amp;router.post_routes);
        let put_routes = Router::protocol_to_tree(amp;router.put_routes);
        let delete_routes = Router::protocol_to_tree(amp;router.delete_routes);
        let patch_routes = Router::protocol_to_tree(amp;router.patch_routes);
        let head_routes = Router::protocol_to_tree(amp;router.head_routes);
        let options_routes = Router::protocol_to_tree(amp;router.options_routes);
        let connect_routes = Router::protocol_to_tree(amp;router.connect_routes);
        let trace_routes = Router::protocol_to_tree(amp;router.trace_routes);

        Self {
            get_routes,
            post_routes,
            put_routes,
            delete_routes,
            patch_routes,
            head_routes,
            options_routes,
            connect_routes,
            trace_routes,
        }
    }

    #[inline(always)]
    fn get_relevant_map(self, route: amp;Method) -> Option<Node<PyFunction>> {
        match route {
            amp;Method::GET => Some(self.get_routes),
            amp;Method::POST => Some(self.post_routes),
            amp;Method::PUT => Some(self.put_routes),
            amp;Method::PATCH => Some(self.patch_routes),
            amp;Method::DELETE => Some(self.delete_routes),
            amp;Method::HEAD => Some(self.head_routes),
            amp;Method::OPTIONS => Some(self.options_routes),
            amp;Method::CONNECT => Some(self.connect_routes),
            amp;Method::TRACE => Some(self.trace_routes),
            _ => None,
        }
    }

    #[inline(always)]
    pub fn get_route(self, route_method: amp;Method, route: amp;str) -> Option<PyFunction> {
        println!("Hello world how are your");
        let table = self.get_relevant_map(route_method)?;

        let x = match table.at(route) {
            Ok(res) => Some(res.value.clone()),
            Err(_) => None,
        };

        x
    }
}

 

и я пытаюсь получить доступ к вызову get_route метода реализации, но получаю ошибку.

 async fn index(
    router: web::Data<Arc<Routing>>,
    headers: web::Data<Arc<Headers>>,
    mut payload: web::Payload,
    req: HttpRequest,
) -> impl Responder {
    let x = match (amp;router)
        .clone()
        .get_route(amp;req.method().clone(), req.uri().path())
        .clone()
    {
        Some(handler_function) => {
            return handle_request(amp;handler_function, amp;headers, amp;mut payload, amp;req).await
        }
        None => {
            let mut response = HttpResponse::Ok();
            apply_headers(amp;mut response, amp;headers);
            return response.finish();
        }
    };

    x
}

 
 [rustc E0507] [E] cannot move out of an `Arc`

move occurs because value has type `router::Routing`, which does not implement the `Copy` trait
 

Полное сообщение об ошибке:

 error[E0507]: cannot move out of an `Arc`
   --> src/server.rs:160:19
    |
160 |       let x = match (amp;router)
    |  ___________________^
161 | |         .clone()
    | |________________^ move occurs because value has type `Routing`, which does not implement the `Copy` trait

error: aborting due to 2 previous errors; 2 warnings emitted

Some errors have detailed explanations: E0308, E0507.
For more information about an error, try `rustc --explain E0308`.
error: could not compile `robyn`
 

Я попытался обернуть свойства структуры в Arc, блокировки, но все еще не могу найти решение.

Любая помощь будет высоко оценена. Заранее спасибо.

Комментарии:

1. Можете ли вы опубликовать полное сообщение об ошибке?

2. get_route() и get_relevant_map() должен принять amp;self , а не self . Принятие себя означает, что они становятся владельцами объекта при вызове, делая его непригодным для вызывающего абонента. Это не требуется для этих функций и несовместимо с объектом, находящимся за ссылкой (что и происходит, когда он находится «внутри» an Arc ).

3. @Aiden4 , я добавил сообщение об ошибке.

4. @user4815162342 , я не думаю, что понимаю вашу точку зрения. Будет ли передача ссылочного объекта по дуге делать его клонируемым?

5. @SanskarJethi Arc делает каждый объект клонируемым, клонируя указатель с подсчетом ссылок. Проблема с вашим кодом (и, я подозреваю, причина, по которой вы ввели все эти вызовы для клонирования) заключается в том, что методы, такие как get_route() и get_relevant_map() принимают self вместо amp;self . Это ненужно и неправильно, поэтому сначала вы должны это изменить.