gpt4 book ai didi

rust - 为什么调用者必须使用构造函数而不是直接创建结构?

转载 作者:行者123 更新时间:2023-11-29 07:56:13 24 4
gpt4 key购买 nike

考虑以下 Rust 片段 from The Rust Programming Language, second edition :

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
}
}

和相应教程的评论,强调我的:

Next, we implement a method named value that borrows self, doesn’t have any other parameters, and returns a u32. This is a kind of method sometimes called a getter, since its purpose is to get some data from its fields and return it. This public method is necessary because the value field of the Guess struct is private. It’s important that the value field is private so that code using the Guess struct is not allowed to set value directly: callers outside the module must use the Guess::new function to create an instance of Guess, which ensures there’s no way for a Guess to have a value that hasn’t been checked by the conditions in the Guess::new function.

为什么调用者必须使用 new 函数?难道他们不能通过执行以下操作来绕过 Guess.value 介于 1 和 100 之间的要求:

let g = Guess { value: 200 };

最佳答案

这仅适用于 Guess 结构在与使用它的代码不同的模块中定义的情况;该结构本身是公共(public)的,但它的 value 字段不是,因此您不能直接访问它。

您可以通过以下示例 ( playground link ) 进行验证:

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
}
}
}

这本书很好地解释了将结构内容保密的基本原理。

关于rust - 为什么调用者必须使用构造函数而不是直接创建结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46711357/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com