请看下面的代码片段锈从锈病编程语言,第二版:
pub struct Guess {
value: u32,
}
impl Guess {
pub fn new(value: u32) -> Guess {
if value < 1 || value > 100 {
panic!("Guess value must be between 1 and 100, got {}.", value);
}
Guess {
value
}
}
pub fn value(&self) -> u32 {
self.value
}
}
Run Code Online (Sandbox Code Playgroud)
和相应教程的评论,强调我的:
接下来,我们实现一个名为
valueborrows 的方法self,没有任何其他参数,并返回一个u32.这是一种有时称为getter的方法,因为它的目的是从其字段中获取一些数据并将其返回.这个公共方法是必要的,因为struct 的value字段Guess是私有的.这是很重要的value领域是私人所以使用的代码Guess结构是不允许设置value直接: 模块外部用户必须使用该Guess::new函数来创建的实例Guess,确保有没有办法为Guess有一个value尚未确认由Guess::new功能中的条件.
为什么呼叫者必须使用该new功能?他们不能通过Guess.value做类似的事情来解决1到100之间的要求:
let g = Guess { value: 200 };
Run Code Online (Sandbox Code Playgroud)
lje*_*drz 10
仅当Guess结构在与使用它的代码不同的模块中定义时才适用; 结构本身是公共的,但它的value字段不是,所以你不能直接访问它.
您可以使用以下示例(playground链接)验证它:
use self::guess::Guess;
fn main() {
let guess1 = Guess::new(20); // works
let guess2 = Guess::new(200); // panic: 'Guess value must be between 1 and 100, got 200.'
let guess3 = Guess { value: 20 }; // error: field `value` of struct `guess::Guess` is private
let guess4 = Guess { value: 200 }; // error: field `value` of struct `guess::Guess` is private
}
mod guess {
pub struct Guess {
value: u32,
}
impl Guess {
pub fn new(value: u32) -> Guess {
if value < 1 || value > 100 {
panic!("Guess value must be between 1 and 100, got {}.", value);
}
Guess {
value
}
}
pub fn value(&self) -> u32 {
self.value
}
}
}
Run Code Online (Sandbox Code Playgroud)
本书解释了保持结构内容非常私密的基本原理.
| 归档时间: |
|
| 查看次数: |
167 次 |
| 最近记录: |