问题
The following code doesn't compile, because it says that requests is not defined when I try to use it in the operations module.
I think this maybe has something to do with importing modules maybe, but I'm really new to rust and don't understand. I thought I could just do module::struct and as long as the struct was public I would be able to access it.
Can someone explain why this doesn't work, and how to make this work?
pub mod vehicles {
pub struct Vehicle {
_vehicle_id: u64,
_capacity: u32,
}
impl Vehicle {
pub fn new(id: u64, cap: u32) -> Vehicle {
Vehicle {
_vehicle_id: id,
_capacity: cap,
}
}
pub fn get_id(&self) -> u64 {
self._vehicle_id
}
pub fn get_capacity(&self) -> u32 {
self._capacity
}
}
}
mod requests {
pub struct Request {
_request_id: u64,
_request_time: i64,
_origin: u64,
_destination: u64,
_assigned: bool,
}
impl Request {
pub fn new(id: u64, time: i64, origin: u64, dest: u64) -> Request {
Request {
_request_id: id,
_request_time: time,
_origin: origin,
_destination: dest,
_assigned: false,
}
}
pub fn get_id(&self) -> u64 {
self._request_id
}
pub fn get_request_time(&self) -> i64 {
self._request_time
}
pub fn get_origin(&self) -> u64 {
self._origin
}
pub fn get_destination(&self) -> u64 {
self._destination
}
pub fn is_assigned(&self) -> bool {
self._assigned
}
}
}
pub mod operations {
#[derive(Clone, Copy)]
pub enum OperationType {
PICKUP,
DROPOFF,
}
pub struct Operation {
_request: requests::Request,
_location: u64,
_operation_type: OperationType,
_expected_time: i64,
}
impl Operation {
pub fn new(request: requests::Request, optype: OperationType, location: u64, time: i64) -> Self {
Self {
_request: request,
_operation_type: optype,
_location: location,
_expected_time: time,
}
}
pub fn get_location(&self) -> u64 {
self._location
}
pub fn get_request(&self) -> &requests::Request {
&self._request
}
pub fn get_type(&self) -> OperationType {
self._operation_type
}
pub fn get_expected_time(&self) -> i64 {
self._expected_time
}
}
}
回答1:
Since Rust 2018, you must use crate keyword, add use crate::requests;
somewhere (generally on the top) in the module where you want use requests
.
See, the relevant module section in the book.
来源:https://stackoverflow.com/questions/60021688/using-a-struct-from-another-module-in-a-new-module