面试题答案
一键面试- 使用
as
关键字重命名:- 在Rust中,可以使用
as
关键字对导入的名称进行重命名,这样即使不同模块调用相同名称的函数,也不会产生命名冲突。 - 项目结构如下:
src/ main.rs util.rs module_a.rs module_b.rs
util.rs
代码:// util.rs pub(crate) fn helper_func() { println!("This is the helper function."); }
module_a.rs
代码:// module_a.rs mod util; pub fn call_helper_a() { util::helper_func(); }
module_b.rs
代码:// module_b.rs mod util; pub fn call_helper_b() { // 重命名为helper_func_b use util::helper_func as helper_func_b; helper_func_b(); }
main.rs
代码:// main.rs mod module_a; mod module_b; fn main() { module_a::call_helper_a(); module_b::call_helper_b(); }
- 在Rust中,可以使用
- 通过不同的路径访问:
- 可以将
util
模块作为不同模块的子模块,这样通过不同的路径来访问helper_func
,避免命名冲突。 - 项目结构如下:
src/ main.rs module_a/ mod.rs util.rs module_b/ mod.rs util.rs
module_a/util.rs
代码:// module_a/util.rs pub(crate) fn helper_func() { println!("This is the helper function in module_a."); }
module_a/mod.rs
代码:// module_a/mod.rs pub mod util; pub fn call_helper_a() { util::helper_func(); }
module_b/util.rs
代码:// module_b/util.rs pub(crate) fn helper_func() { println!("This is the helper function in module_b."); }
module_b/mod.rs
代码:// module_b/mod.rs pub mod util; pub fn call_helper_b() { util::helper_func(); }
main.rs
代码:// main.rs mod module_a; mod module_b; fn main() { module_a::call_helper_a(); module_b::call_helper_b(); }
- 可以将
以上两种方法都能在保持helper_func
封装性的同时,解决潜在的命名冲突问题。第一种方法适用于不同模块对同一工具函数有不同调用逻辑但希望复用同一工具函数定义的情况;第二种方法适用于不同模块对工具函数的实现也有差异的情况。