You can fix this issue in 2 different ways:
1 ) Using Module
2 ) Using Library
Using Module
Simply create a file next to main.rs in src directory and name it name1.rs
name1.rs will look like:
//no need to specify "pub mod name1;" explicitly
pub fn name(a: i32) -> i32 {
println!("from diff file {}", a);
a * a
}
main.rs will look like:
//name of the second file will be treated as module here
pub mod name1;
fn main() {
println!("{}", name1::name(4));
}
Using Library
a) create a library, standing in main project directory (i.e. parent of src directory) and run the command below:
//In your case library name "file"
$ cargo new --lib file
This command will create another directory of name file same as your main project.
b) Add this library(file) in the dependency section of Cargo.toml file of main project
[package]
name = "test_project"
version = "0.1.0"
authors = ["mohammadrajabraza <mohammadrajabraza@gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
file = {path ="file"}
c) A file under main_project>file(library)>src>lib.rs will be created, once you created library using command above.
lib.rs will be look like:
pub fn name(a: i32) -> i32 {
println!("from diff file {}", a);
a * a
}
d) and finally your main.rs will be:
//importing library in thescope
use file;
fn main() {
println!("{}", file::name(4));
}