0

I have the following directory structure in my Rust project:

borrowing
   |
   |-------src
   |        |-------borrow.rs
   |        |-------lib.rs
   | 
   |-------Cargo.toml
   |-------main.rs 

borrow.rs

pub fn simple_borrow() {
    let _a = 10;
    let _b = 20;
    let _b = _a;
    println!("a:{}, b: {}", _a, _b);
}

lib.rs

mod borrow;

main.rs

use borrow;

fn main()
{
    borrow::simple_borrow();
}

Cargo.toml

[package]
name = "borrower"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

[[bin]]
name="borrowery"
path="main.rs"

The above is giving me the following error:

C:\git\Rust examples\borrowing>cargo run
   Compiling borrower v0.1.0 (C:\git\Rust examples\borrowing)
warning: function `simple_borrow` is never used
 --> src\borrow.rs:1:8
  |
1 | pub fn simple_borrow() {
  |        ^^^^^^^^^^^^^
  |
  = note: `#[warn(dead_code)]` on by default

warning: `borrower` (lib) generated 1 warning
error[E0432]: unresolved import `borrow`
 --> main.rs:1:5
  |
1 | use borrow;
  |     ^^^^^^ no external crate `borrow`
  |
help: consider importing one of these items instead
  |
1 | use core::borrow;
  |     ~~~~~~~~~~~~~
1 | use std::borrow;
  |     ~~~~~~~~~~~~

For more information about this error, try `rustc --explain E0432`.
error: could not compile `borrower` due to previous error

C:\git\Rust examples\borrowing>

How can I resolve the error?

user366312
  • 16,949
  • 65
  • 235
  • 452
  • The package name of library is `borrower`, and the borrow is not defined public, if you define it as `pub borrow` then you can use it in your main.rs like this: `use borrower::borrow;` – Ömer Erden Mar 06 '23 at 17:05

1 Answers1

2

Your code has 2 errors, the first is you're using the wrong path for the module, src/lib.rs and every binary, in your case main.rs are in different crates, therefore instead of the relative path borrow you have to use the full path, including the crate name, which defaults to the packages name: borrower::borrow:

use borrower::borrow;

Then Rust will tell you that the module borrow is private and you can't use it. To make it public you can simply use the pub keyword in front of the module declaration in src/lib.rs:

pub mod borrow;
cafce25
  • 15,907
  • 4
  • 25
  • 31