面试题答案
一键面试Rust模块系统可见性规则
pub
关键字作用:在Rust中,pub
关键字用于将结构体、函数、模块等项设置为公共的,即可以从定义它们的模块之外访问。默认情况下,Rust中的所有项(结构体、函数、模块等)都是私有的,只能在定义它们的模块内部访问。通过在项前加上pub
,可以改变其可见性,允许外部代码访问。- 结构体字段可见性:即使结构体被声明为
pub
,其字段默认也是私有的。要使结构体字段可被外部访问,每个字段都需要单独标记为pub
。例如:
pub struct Point {
pub x: i32,
y: i32
}
在上述代码中,Point
结构体是pub
的,但只有x
字段是可从外部访问的,y
字段仍然是私有的。
模块架构设计示例
假设我们正在设计一个图形库graphic_lib
,它有以下需求:
- 有一个
shapes
模块用于定义各种形状相关的结构体和函数。 shapes
模块下有circle
和rectangle
子模块,分别处理圆形和矩形相关逻辑。- 库内部有一个
utils
模块用于一些通用的工具函数,shapes
模块下的子模块需要使用utils
模块的功能,但utils
模块不应该暴露给外部调用。 circle
模块中的calculate_area
函数需要暴露给外部调用,而rectangle
模块中的private_helper_function
函数只供rectangle
模块内部使用。
// 顶级模块
pub mod shapes {
// 导入utils模块,使其在shapes模块内可用
mod utils;
// circle子模块
pub mod circle {
use super::utils::distance;
// 定义Circle结构体并使其公共
pub struct Circle {
pub radius: f64,
}
// 定义calculate_area函数并使其公共
pub fn calculate_area(circle: &Circle) -> f64 {
std::f64::consts::PI * circle.radius * circle.radius
}
}
// rectangle子模块
pub mod rectangle {
use super::utils::distance;
// 定义Rectangle结构体并使其公共
pub struct Rectangle {
pub width: f64,
pub height: f64,
}
// 定义private_helper_function函数,只供rectangle模块内部使用
fn private_helper_function(rect: &Rectangle) -> f64 {
rect.width * rect.height
}
// 定义calculate_area函数并使其公共
pub fn calculate_area(rect: &Rectangle) -> f64 {
private_helper_function(rect)
}
}
}
// utils模块,仅在库内部使用
mod utils {
// 定义distance函数,供shapes模块下的子模块使用
pub fn distance(x1: f64, x2: f64) -> f64 {
(x1 - x2).abs()
}
}
可见性设置说明
- 顶级模块:
shapes
模块被声明为pub
,这样外部代码可以访问shapes
模块及其子模块中的公共项。utils
模块没有声明为pub
,所以它对外部代码不可见。 - 子模块:
circle
和rectangle
子模块在shapes
模块下被声明为pub
,外部代码可以访问它们的公共项。 - 结构体:
Circle
和Rectangle
结构体在各自的子模块中被声明为pub
,并且它们的部分字段也被声明为pub
,这样外部代码可以访问这些结构体及其公共字段。 - 函数:
circle
模块中的calculate_area
函数被声明为pub
,可以被外部代码调用。rectangle
模块中的private_helper_function
函数没有声明为pub
,只能在rectangle
模块内部使用,而calculate_area
函数是pub
的,可被外部调用。 - 模块间访问:
circle
和rectangle
子模块通过use super::utils::distance
语句使用utils
模块中的distance
函数,因为distance
函数被声明为pub
,所以在shapes
模块及其子模块内可访问。