簡體   English   中英

如何從子模塊中的結構訪問私有字段?

[英]How can I access a private field from a struct in a submodule?

我想將我的 rust 模塊拆分為單獨的文件。 所以我使用了一個子模塊。 問題是我無法從子模塊中定義的結構訪問私有字段。 這是一個例子:

// mod1.rs
mod point;

struct Point1 {
    x: i32,
    y: i32,
}

impl Point1 {
    pub fn new(x: i32, y: i32) -> Point1 {
        Point1 { x: x, y: y }
    }
}

pub fn run() {
    let a = Point1::new(1, 2);
    let b = point::Point2::new(3, 4);

    println!("{}, {}", a.x, a.y); // 1, 2
    println!("{}, {}", b.x, b.y); // error
}

// point.rs
pub struct Point2 {
    x: i32,
    y: i32,
}

impl Point2 {
    pub fn new(x: i32, y: i32) -> Point2 {
        Point2 { x: x, y: y }
    }
}

如何將代碼拆分為單獨的文件並仍然訪問結構的私有成員?

您可以使用pub (super)將某些內容僅對其父模塊公開。

pub struct Point2 {
    pub (super) x: i32,
    pub (super) y: i32,
}

查看有關可見性和隱私的 rust 文檔。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM