[SOLVED] 2018 Importing lib.rs from main.rs

#1

Hi hi!

I’ve been having some trouble with this issue and I can’t find any documentation on what I’m doing wrong.

I’m working on a crate graphdb. I’m trying to build a binary at src/bin/main.rs that. uses the code from src/lib.rs. However, I can’t get the use statements set up correctly.

My Cargo.toml file is pretty simple:

[package]
name = "graph-db"
version = "0.1.0"
authors = ["Robbie McKinstry <redacted@redacted.com>"]
edition = "2018"

[lib]
name = "graph"
path = "src/lib.rs"

[[bin]]
name = "graph"
path = "src/bin/main.rs"

[dependencies]
omitted for clarity

My src/lib.rs looks like this:

pub use json_reader::read_json_edges;
mod json_reader;

My main file is super simple:

use crate::read_json_edges;

  fn main() {
      if let Some(x) = read_json_edges("sample_data/slashdot.json") {
          println!("{:?}", x);
      }
  }

And my source code is present:
In src/json_reader.rs:

pub fn read_json_edges(filepath: &str) -> Result<Vec<Edge>>  {
    omitted for brevity...
}

The error I’m getting is

error[E0432]: unresolved import `crate::read_json_edges`
 --> src/bin/main.rs:1:5
  |
1 | use crate::read_json_edges;
  |     ^^^^^^^^^^^^^^^^^^^^^^ no `read_json_edges` in the root

I have no problem running my test suite. My RLS seems to be able to find my crate well enough. But for whatever reason running cargo build produces the above error. I’ve looked around for other examples of this pattern but I can’t find anything using the 2018 modules; doing what worked in versions < 2018 has not yielded any results. I’ve tried similar things like trying to import crate::json_reader::read_json_edges directly.

Any help would be greatly appreciated. Thank you for your time and attention, friends.

#2

Does

/// ::crate-lib-name::path::to::item;
use ::graph::read_json_edges;

work for you?

(crate refers to the current crate, in your case the bin crate)

1 Like
#3

You’re a God send. The above throws an error saying json_reader is private (which surprises me), but I got it to work with use graph::read_json_edges;!

Thank you thank you thank you!

1 Like
#4

Yep, at the beginning it can be troubling that once you leave the lib realm (be it as a bin, an example, or an integration test), you become an external user of your crate :wink: