简体   繁体   English

Rust中的公共/私有结构

[英]Public/Private struct in Rust

I have a little project and I want to encapsulate a struct's fields and use implemented methods. 我有一个小项目,我想封装一个struct的字段并使用实现的方法。

├── src
├── main.rs
├── predator
└── prey
   ├── cycle.rs
   └── mod.rs

cycle.rs cycle.rs

struct Prey {
    name: String,
}

impl Prey {
    pub fn new(n: String) -> Prey {
        Prey { name: n }
    }

    pub fn get_name(&self) -> &str {
        self.name.as_str()
    }
}

I'd like to leave Prey as private. 我想把Prey留给私人。

main.rs main.rs

use prey::cycle::Prey;
mod prey;

fn main() {
    let pr = Prey::new("Hamster".to_string());
    println!("Hello, world! {}", pr.get_name());
}

I get an error: 我收到一个错误:

error: struct `Prey` is private

I know that if I put pub before struct Prey {} , I'll get the expected result. 我知道如果我在struct Prey {}之前放置pub ,我会得到预期的结果。 I will be grateful for an explanation, how, why not and/or best practices. 我将很感激解释,如何,为什么不和/或最佳实践。

Visibility works at the module level. 可见性适用于模块级别。 If you want module X to have access to an item in module Y, module Y must make it public. 如果您希望模块X可以访问模块Y中的项目 ,则模块Y必须将其公开。

Modules are items too. 模块也是项目。 If you don't make a module public, then it's internal to your crate. 如果你没有公开一个模块,那么它就是你的箱子的内部。 Therefore, you shouldn't worry about making items in that module public; 因此,您不必担心将该模块中的项目公开; only your crate will have access to it. 只有您的箱子才能访问它。

The crate root (usually the file named lib.rs or main.rs ) is the root module of your crate. 包根(通常是名为lib.rsmain.rs的文件)是您的包的根模块。 It defines the public interface of the crate, ie public items in the crate root are accessible from other crates. 它定义了板条箱的公共接口,即板条箱根目录中的公共项目可以从其他板条箱中访问。

In your example, you write mod prey; 在你的例子中,你写了mod prey; . That defines the prey module as private, so items in the prey module are not accessible from other crates (unless you reexport them with pub use ). 这将prey模块定义为私有模块,因此无法从其他条板箱访问prey模块中的项目(除非您使用pub use导出它们)。 That means you should make prey::cycle::Prey public. 这意味着你应该让prey::cycle::Prey公开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM