如何在 main.rs 中导入函数

bic*_*nna 4 import rust rust-crates

这可能是一个愚蠢的问题,但我似乎无法解决这个问题。

\n

我有这样的文件结构:

\n
\xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 src\n    \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 another.rs\n    \xe2\x94\x9c\xe2\x94\x80\xe2\x94\x80 some_file.rs\n    \xe2\x94\x94\xe2\x94\x80\xe2\x94\x80 main.rs\n
Run Code Online (Sandbox Code Playgroud)\n

在 中some_file.rs,我想调用 中的函数main.rs。所以,我尝试在some_file.rs

\n
use crate::main\n\n\nfn some_func() {\n   // other code\n   \n   main::another_func_in_main();\n}\n
Run Code Online (Sandbox Code Playgroud)\n

但编译器会抛出错误:

\n
use of an undeclared crate or module `main`\n
Run Code Online (Sandbox Code Playgroud)\n

我该如何解决这个问题?

\n

at5*_*321 6

main即使您有文件,也没有模块main.rs。您放入文件中的内容main.rs被视为位于crate 的根目录下。

所以你有两种方法来调用该函数:

1. 直接(不使用)

crate::another_func_in_main();
Run Code Online (Sandbox Code Playgroud)

2.先导入

use crate::another_func_in_main;

// Then in code, no need for a prefix:
another_func_in_main();
Run Code Online (Sandbox Code Playgroud)

  • 评论链接 /sf/ask/1464546401/ 和 /sf/ask/4287145831/ (指出您还可以使用“super::”作为相对于当前的模块路径模块) (2认同)