为什么 rust 让我实例化一个 `pub struct ... {private: ...}` 为 `let var = ...{private: ...};` 但不能访问 `var.private` ?

问题描述 投票:0回答:1

我有一个生锈的箱子,基本上看起来像这样:

// src/mymod.rs
pub mod submod_a;
pub mod submod_b;

// src/mymod/submod_a.rs
pub struct FooA { bar: () }                           // private
// src/mymod/submod_b.rs
pub struct FooB { bar: () }                           // private


// src/main.rs
mod mymod;
use mymod::{submod_a::FooA, submod_b::FooB};
fn main() {
    let aa = FooA{bar: ()};                           // "private" use ok here
    let bb = FooB{bar: ()};                           // "private" use ok here

    println!("aa = {:?}, bb = {:?}", aa.bar, bb.bar); // compile error here
}

如前所述,如果我尝试显式访问“私有”成员,我会收到编译错误,但我可以使用/指定此“私有”成员构造此实例:

   Compiling testproj v0.1.0 (/home/fhofmann/build/testproj)
error[E0616]: field `bar` of struct `FooA` is private
 --> src/main.rs:6:41
  |
6 |     println!("aa = {:?}, bb = {:?}", aa.bar, bb.bar);
  |                                         ^^^ private field

error[E0616]: field `bar` of struct `FooB` is private
 --> src/main.rs:6:49
  |
6 |     println!("aa = {:?}, bb = {:?}", aa.bar, bb.bar);
  |                                                 ^^^ private field

For more information about this error, try `rustc --explain E0616`.
error: could not compile `testproj` (bin "testproj") due to 2 previous errors

我对此感到惊讶;我本以为尝试初始化

struct FooA
/
struct FooB
会给我带来与尝试从
FooA::bar
范围访问
FooB::bar
/
main()
相同的错误。这是为什么?

rust
1个回答
0
投票

你可以这样做:

pub struct FooA {
    bar: (),
}

impl FooA {
    pub fn new(bar: ()) -> Self {
        FooA { bar }
    }
}

// and this will work:

fn main() {
    let aa = FooA::new(());
}

getter
相同。

© www.soinside.com 2019 - 2024. All rights reserved.