发布于 2015-07-16 14:22:07 | 230 次阅读 | 评论: 3 | 来源: 网络整理

Rust可视性

结构有可见性的一个额外的级别,它们的字段可以是公共或私有的(这是默认值)。这种可见只有当结构是从那里它被定义的模块外部访问重要的,它的目标是信息隐藏(封装)。


mod my {
    // A public struct with public fields
    pub struct WhiteBox {
        pub contents: T,
    }

    // A public struct with private fields
    #[allow(dead_code)]
    pub struct BlackBox {
        contents: T,
    }

    impl BlackBox {
        // A public constructor
        pub fn new(contents: T) -> BlackBox {
            BlackBox {
                contents: contents,
            }
        }
    }
}

fn main() {
    // Public structs with public fields can be constructed as usual
    let white_box = my::WhiteBox { contents: "public information" };

    // and their fields can be normally accessed
    println!("The white box contains: {}", white_box.contents);

    // but public structs with private fields can't be constructed
    // Error! `BlackBox` has private fields
    //let black_box = my::BlackBox { contents: "classified information" };
    // TODO ^ Try uncommenting this line

    // However, structs with private fields can still be created using
    // constructors
    let _black_box = my::BlackBox::new("classified information");

    // The private fields of a struct can't be accessed
    // Error! The `contents` field is private
    //println!("The black box contains: {}", _black_box.contents);
    // TODO ^ Try uncommenting this line
}
最新网友评论  共有(3)条评论 发布评论 返回顶部
bug 发布于2016-08-24 01:42:08
我点击了“支持”,然后还能点击“反对”,这就不合逻辑了
支持(0)  反对(0)  回复
check 发布于2016-08-24 01:40:54
这个后台逻辑有待优化
支持(0)  反对(0)  回复
fsh 发布于2016-08-24 01:39:33
一定好好学学
支持(1)  反对(1)  回复

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务