1

Problem

Cannot access ServerConnection which is in /src/gameclient/server_connection.rs from /src/bin/client.rs.

I dont have any lib.rs nor main.rs all binaries are in /src/bin/

Project structure

enter image description here

Cargo.toml

...
[[bin]]
name = "server"
path = "src/bin/server.rs"

[[bin]]
name = "client"
path = "src/bin/client.rs"
...

/src/gameclient/mod.rs

rust-analyzer already complains here with:

file not included in module tree

pub mod player_instance;
pub use crate::gameclient::player_instance::PlayerInstance;

pub mod server_connection;
pub use crate::gameclient::server_connection::ServerConnection;

/src/gameclient/server_connection/ServerConnection

...
pub struct ServerConnection {
    pub server_endpoint: url::Url,
}

pub impl ServerConnection {
    pub fn connect(&self) {
...
MortalFool
  • 1,065
  • 2
  • 14
  • 26
  • When i add a `lib.rs` with `pub mod gameclient;` it works. So is a `lib.rs` always required in such cases? – MortalFool Aug 24 '22 at 19:03
  • 2
    You need to have `mod gameclient` somewhere, whether that be in `bin/client.rs` with a [`#[path =]` attribute](https://doc.rust-lang.org/reference/items/modules.html#the-path-attribute) or in a `lib.rs` that gets used in `bin/client.rs`. Generally a crate will have a `lib.rs`. – PitaJ Aug 24 '22 at 19:04

1 Answers1

0

Pitaj gave the correct answer already.

Just for completeness.

/src/bin/client.rs

adding this at the very top makes me get rid of lib.rs.

#[path = "../gameclient/mod.rs"]
mod gameclient;
MortalFool
  • 1,065
  • 2
  • 14
  • 26
  • 1
    It is unclear why you wanted to avoid having a library (using `lib.rs`) in the first place. In the event that a module is used in multiple binaries, this approach would replicate the library modules to each one of them. – E_net4 Aug 26 '22 at 09:45
  • I was desparte and did not understand the [Module doc](https://doc.rust-lang.org/reference/items/modules.html#the-path-attribute). Now i think a cleaner solution would be to have 3 separate Cargo.toml subprojects. client, server, and sharedlibs and the main will just container the README.md with the project documentation. – MortalFool Aug 26 '22 at 10:39
  • 1
    There are much better resources for learning how the module system works: the book has an entire [chapter](https://doc.rust-lang.org/stable/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html) on it. See also these other questions: https://stackoverflow.com/questions/26946646/package-with-both-a-library-and-a-binary https://stackoverflow.com/questions/57756927/rust-modules-confusion-when-there-is-main-rs-and-lib-rs https://stackoverflow.com/questions/26388861/how-can-i-include-a-module-from-another-file-from-the-same-project – E_net4 Aug 26 '22 at 10:43