Rust 编程中的结构可见性
Rust 中的结构包含额外的可见性级别。这些级别可以根据开发人员的便利性进行修改。
在正常情况下,Rust 中的struct 的可见性是私有的,可以使用 pub 修饰符将其变为公有。
需要注意的是,只有当我们尝试从定义模块外部访问 struct 字段时,这种可见性情况才有意义。
当我们隐藏struct 的字段时,我们只是试图封装数据。
示例
考虑下面显示的示例 −
mod my {
// A public struct with a public field of generic type `T`
pub struct OpenStruct {
pub contents: T,
}
// A public struct with a private field of generic type `T`
#[allow(dead_code)]
pub struct ClosedStruct {
contents: T,
}
impl ClosedStructx {
// A public constructor method
pub fn new(contents: T) -> ClosedStruct {
ClosedStrut {
contents: contents,
}
}
}
}
fn main() {
// Public structs with public fields can be constructed as usual
let open_box = my::OpenStruct {
contents: "public information"
};
// and their fields can be normally accessed.
println!("The open box contains: {}", open_box.contents);
}在上面的代码中,我们创建了两个 struct,它们本质上都是公有的,但是其中一个 struct 的字段设置为公有,而另一个 struct 的字段是私有的。稍后在 main 函数中,我们尝试构造名为 OpenStruct 的公有 struct 的公有字段,然后打印该字段。
输出
The open box contains: public information
一切都运行良好。但是,如果现在我们尝试访问名为 ClosedStruct 的结构,以及它的字段,就像我们对 OpenStruct 所做的那样,我们将发生此错误。
代码
let closed_box = my::ClosedBox { contents: "classified information" };我们将得到一个错误。
输出
error[E0451]: field `contents` of struct `ClosedBox` is private
--> src/main.rs:32:38
|
32| let closed_box = my::ClosedBox { contents: "classified
information" };
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ private field尽管值得注意的是,可以使用公共构造函数创建具有私有字段的结构,但我们仍然无法访问私有字段。
let _closed_box = my::ClosedBox::new("classified information");它将正常工作。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP