简体   繁体   English

如何在 Rust 的 main.rs 中导入 function

[英]How to import a function in main.rs in Rust

This may be a stupid question, but I cannot seem to solve this.这可能是一个愚蠢的问题,但我似乎无法解决这个问题。

I have this kind of file structure:我有这种文件结构:

└── src
    ├── another.rs
    ├── some_file.rs
    └── main.rs

In the some_file.rs , I want to call a function in the main.rs .some_file.rs中,我想在main.rs中调用 function 。 So, I tried to do something like this in the some_file.rs :所以,我尝试在some_file.rs中做这样的事情:

use crate::main


fn some_func() {
   // other code
   
   main::another_func_in_main();
}

But the compiler throws an error:但是编译器会抛出一个错误:

use of an undeclared crate or module `main`

How can I solve this?我该如何解决这个问题?

There is no main module, even though you have a main.rs file.没有main模块,即使您有一个main.rs文件。 The stuff you put in the main.rs file are considered to be at the root of the crate.你放在main.rs文件中的东西被认为是 crate 的根目录

So you have two ways to call the function:所以你有两种方法可以调用 function:

1. Directly (w/o use) 1. 直接(不使用)

crate::another_func_in_main();

2. By importing it first 2.先导入

use crate::another_func_in_main();

// Then in code, no need for a prefix:
another_func_in_main();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM