I have such a directory structure:
structs
-book.rs
main.rs
I just read about modules and am trying to import a structure from book.rs in main:
book.rs
#[derive(Debug)]
pub struct book{
pub title:u32
}
main.rs
mod book;
fn main() {
print!("start")
}
And this causes an error: unresolved module, can't find module file: book.rs , or book/mod.rs
I tried in different ways, but it doesn't work out. I will be glad of help to understand what the error is.
You need to make structs a module to be able to import things.
structs
-book.rs
-mod.rs
main.rs
main.rs
mod structs;
use crate::structs::book::book;
fn main() {
let b = book {
title: "The Rust Programming Language".to_string(),
};
print!("{:?}", b);
}
structs/mod.rs
pub mod book;
structs/book.rs
#[derive(Debug)]
pub struct book{
pub title: String,
}
You should also change book to be Book when you define the struct since structs should be in PascalCase not camelCase or snake_case
Related
I have the following code in src/
main.rs
a.rs
b.rs
Here's the code:
main.rs
mod a;
mod b;
use crate::a::Summary;
use crate::b::Person;
fn main() {
let p = Person{ first: "John".to_string(), last: "Doe".to_string() } ;
sum(p) ;
}
fn sum(summary: impl Summary) {
println!("{}", summary.summarize()) ;
}
a.rs
pub trait Summary {
fn summarize(&self) -> String ;
}
b.rs
use crate::Summary;
pub struct Person {
pub first: String,
pub last: String,
}
impl Summary for Person {
fn summarize(&self) -> String {
format!("{}, {}.", self.last, self.first)
}
}
What I don't understand is how does "use crate::Summary;" not cause a problem in b.rs? It should be "use crate::a::Summary;" or even "use super::a::Summary;", but for some reason use crate::Summary works. Is there some kind of funky search logic being applied here under the hood?
Items defined without a visibility specifier are available to the module that they're defined in and all of its sub-modules.
Since a and b are submodules of the crate root module, they can access the Summary object that was imported via a use declaration in main into the crate root module.
Here's the code:
use crate::rooms::room::RoomInterface;
pub mod dogroom {
pub struct R;
impl RoomInterface for R {
}
}
Here's /rooms/mod.rs:
pub mod room {
// Irrelevant stuff
pub trait RoomInterface {
// stuff
}
// stuff
}
Here's what it tells me:
I find it quite arcane that I import the very same thing it wants me to import, and yet it doesn't work.
I've tried pretty much all the permutations of the use keyword, and I can't make it work. What's going on?
uses are scoped to the module that imports them, not the file they are in.
Move the import into the dogroom module:
pub mod dogroom {
use crate::rooms::room::RoomInterface;
pub struct R;
impl RoomInterface for R {
}
}
Alternatively, you might want the dogroom module to reuse everything from the parent module:
use crate::rooms::room::RoomInterface;
pub mod dogroom {
use super::*;
pub struct R;
impl RoomInterface for R {
}
}
I am trying to share a struct between two files, but I am getting an error.
I have the following folder structure:
src/
Models/
Login.rs
Routes/
LoginRoute.rs
Services/
LoginService.rs
main.rs
In Login.rs I have:
#[derive(Serialize, Deserialize, Debug)]
pub struct UserLoginResponse {
id: i32,
username: String,
token: String
}
In LoginRoute.rs I have:
#[path = "../Models/Login.rs"]
pub mod Login;
#[path = "../Services/LoginService.rs"]
pub mod LoginService;
#[post("/login", format = "application/json", data = "<user>")]
pub async fn login(user: String) -> Json<Login::UserLoginResponse> {
if let Ok(sk) = LoginService::callAuthenticate(user).await {
return sk
......
In LoginService.rs I have:
#[path = "../Models/Login.rs"]
pub mod Login;
pub async fn callAuthenticate(user: String)-> Result<Json<Login::UserLoginResponse>, Error> {
...
let userLoginResponse :Login::UserLoginResponse = Login::UserLoginResponse::new(1, "admin".to_string(), api_reponse.return_result);
Ok(Json(userLoginResponse))
}
I am getting error in LoginRoute.rs on the return sk line:
expected struct 'LoginRoute::Login::UserLoginResponse', found struct 'LoginService::Login:UserLoginResponse'
Please do not use the #[path = ...] attribute for your typical organization; it should only be used in obscure cases. Each time you do mod something, you are declaring a new module. Even if two modules point to the same file due to #[path = ...], they will be distinct.
So you have multiple UserLoginResponse structs declared:
one at crate::LoginRoute::Login::UserLoginResponse
one at crate::LoginService::Login:UserLoginResponse
and maybe another if you've also declared Login in main.rs.
Since they're in distinct modules, the Rust compiler sees them as different types, which is not what you want.
Just use the idiomatic way of declaring modules. If you want to keep your existing folder structure without intermediate mod.rs files, you can declare them all in main.rs like so:
mod Models {
pub mod Login;
}
mod Routes {
pub mod LoginRoute;
}
mod Services {
pub mod LoginService;
}
And then access them elsewhere via crate::Models::Login and whatnot.
See:
How do I import from a sibling module?
You've probably already run into warnings from the compiler trying to encourage a specific style: "module [...] should have a snake case name". Idiomatic file structure would typically look like this:
src/
models/
login.rs
mod.rs
routes/
login_route.rs
mod.rs
services/
login_service.rs
mod.rs
main.rs
Where main.rs would have:
mod models;
mod routes;
mod services;
And src/models/mod.rs (for example) would have:
pub mod login;
I must admit, I am having a hard time making sense of the Rust compiler error messages.
I have this module:
src/adapters.js
use actix_web::{Responder, HttpResponse};
pub mod Basic {
pub fn api_index() -> &'static str {
"API"
}
pub fn admin_index() -> impl Responder {
HttpResponse::Ok().body("hello world!")
}
}
The Rust compiler keeps telling me when I use
use crate::actix_web::{Responder, HttpResponse};
that:
E0432: unresolved import `crate::actix_web` maybe a missing crate `actix_web`?
Rest assured, crate::actix_web is not missing, because I can run simple requests from main.rs. The problem starts when I want to use the actix_web modules within my own modules.
If I have
use actix_web::{Responder, HttpResponse};
Rust keeps teeling me:
error[E0433]: failed to resolve: use of undeclared type or module `HttpResponse`
HttpResponse::Ok().body("hello world!")
^^^^^^^^^^^^ not found in this scope
help: consider importing one of these items
use actix_web::HttpResponse;
use crate::adapters::HttpResponse;
E0432: unresolved import `crate::actix_web` maybe a missing crate `actix_web`?
I my main.rs, as the first line, I've also declared:
extern crate actix_web;
For the sake of making sure, I've also added "extern crate actix_web;" to the adapters.rs module right at the start. That didn't change anything either.
I am running out of options, I don't know what else I could possibly do.
Basically You have created one another module Basic inside adapters module.So Basic is submodule of adapters module. So two ways you can access the external crate in this case.
Import external crate modules inside your Basic Module.
pub mod Basic {
use actix_web::{Responder, HttpResponse};
pub fn api_index() -> &'static str {
"API"
}
pub fn admin_index() -> impl Responder {
HttpResponse::Ok().body("hello world!")
}
}
Or import an external module in outer module module and access those module using use super keyword in inner module.
use actix_web::{Responder, HttpResponse};
pub mod Basic {
pub fn api_index() -> &'static str {
"API"
}
pub fn admin_index() -> impl super::Responder {
super::HttpResponse::Ok().body("hello world!")
}
}
How do I access my libraries exported functions inside the create's "tests" directory?
src/relations.rs:
#![crate_type = "lib"]
mod relations {
pub fn foo() {
println!("foo");
}
}
tests/test.rs:
use relations::foo;
#[test]
fn first() {
foo();
}
$ cargo test
Compiling relations v0.0.1 (file:///home/chris/github/relations)
/home/chris/github/relations/tests/test.rs:1:5: 1:14 error: unresolved import `relations::foo`. Maybe a missing `extern crate relations`?
/home/chris/github/relations/tests/test.rs:1 use relations::foo;
^~~~~~~~~
If I add the suggested extern crate relations, the error is:
/home/chris/github/relations/tests/test.rs:2:5: 2:19 error: unresolved import `relations::foo`. There is no `foo` in `relations`
/home/chris/github/relations/tests/test.rs:2 use relations::foo;
^~~~~~~~~~~~~~
I want to test my relations in this separate tests/test.rs file. How can I solve these use issues?
Your problem is that, first, mod relations is not public so it is not visible outside of the crate, and second, you don't import your crate in tests.
If you build your program with Cargo, then the crate name will be the one you defined in Cargo.toml. For example, if Cargo.toml looks like this:
[package]
name = "whatever"
authors = ["Chris"]
version = "0.0.1"
[lib]
name = "relations" # (1)
And src/lib.rs file contains this:
pub mod relations { // (2); note the pub modifier
pub fn foo() {
println!("foo");
}
}
Then you can write this in tests/test.rs:
extern crate relations; // corresponds to (1)
use relations::relations; // corresponds to (2)
#[test]
fn test() {
relations::foo();
}
The solution was to specify a crate_id at the top of src/relations.rs:
#![crate_id = "relations"]
#![crate_type = "lib"]
pub fn foo() {
println!("foo");
}
This seems to declare that all the contained code is part of a "relations" module, though I'm still not sure how this is different to the earlier mod block.