0

Here is the situation. I have a project named project_name and it has this file hierarchy:

project_name
|-- src
|   |-- main.rs
|   |-- lib.rs
|   `-- tree_node.rs

I declared struct TreeNode in tree_node.rs.

pub struct TreeNode { ... }

There is method using TreeNode in lib.rs:

mod tree_node;

use tree_node::TreeNode;

pub struct Solution {}

impl Solution {
    pub fn invert_tree(root: TreeNode) -> TreeNode { ... }
}

But when I try to use method invert_tree in main.rs like this:

use project_name::Solution;
use tree_node::TreeNode;

mod tree_node;

fn main() {
    let tree = TreeNode::new(1);
    let result = Solution::invert_tree(tree);
}

I got an error:

expected struct `project_name::tree_node::TreeNode`, found struct
`tree_node::TreeNode`

Maybe I use incorrectly term method but I hope the main point is clear. What is wrong?

E_net4
  • 27,810
  • 13
  • 101
  • 139
xneg
  • 1,204
  • 15
  • 24
  • 1
    The duplicate applied to your question: declare the module `tree_node` only in the library root module (lib.rs), then use the library as a crate in main.rs to import its capabilities. – E_net4 Jun 03 '20 at 11:09
  • See also: https://stackoverflow.com/questions/22596920/split-a-module-across-several-files and https://stackoverflow.com/questions/30677258/how-do-i-import-from-a-sibling-module – E_net4 Jun 03 '20 at 11:11
  • Maybe this question duplicates somehow others but I think the answer proposed by @orlp is much shorter. – xneg Jun 03 '20 at 11:24

1 Answers1

1

main.rs and lib.rs are effectively different crates that are compiled separately, and so mod creates separate modules for each when using in both lib and main. Generally you want to only use mod in lib.rs unless some module is only for private use of the application.

Therefore, replace mod tree_node from main.rs with use project_name::tree_node::TreeNode;.

In lib.rs you must change mod tree_node to pub mod tree_node, or pub(crate) mod tree_node if it's only intended for this crate and not outside users.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
orlp
  • 112,504
  • 36
  • 218
  • 315
  • 1
    or else one can declare `TreeNode` in the lib.rs as: `pub use tree_node::TreeNode;` if only wants to expose `TreeNode` from the inner module. – Ömer Erden Jun 03 '20 at 11:09