面试题答案
一键面试在Rust中,可以通过mod
关键字来定义模块,使用pub
关键字来控制模块内函数和结构体的可见性。对于只能被外层模块访问的函数或结构体,不使用pub
关键字声明。
示例代码如下:
// 外层模块
mod outer {
// 内层模块
mod inner {
// 只能被外层模块访问的函数
fn inner_function() {
println!("This is an inner function.");
}
// 只能被外层模块访问的结构体
struct InnerStruct {
data: i32,
}
impl InnerStruct {
fn new(data: i32) -> InnerStruct {
InnerStruct { data }
}
}
// 内层模块中对外可见的函数,用于调用内层不可见的函数和结构体
pub fn call_inner() {
let inner_struct = InnerStruct::new(42);
inner_function();
println!("Inner struct data: {}", inner_struct.data);
}
}
// 外层模块中可调用内层模块函数
pub fn outer_function() {
inner::call_inner();
}
}
fn main() {
// 调用外层模块函数
outer::outer_function();
}
在上述代码中:
outer
模块是外层模块,包含inner
内层模块。inner
模块中的inner_function
和InnerStruct
没有使用pub
关键字,因此它们只能被inner
模块内部以及包含它们的outer
模块访问。inner
模块中的call_inner
函数使用pub
关键字,这样outer
模块可以通过inner::call_inner
调用它,间接调用inner_function
和InnerStruct
。outer
模块中的outer_function
函数使用pub
关键字,这样在main
函数中可以通过outer::outer_function
调用它,进而执行内层模块的功能。