Drawer Level Visibility

I have two types, each of which contains many supporting functions; all content of these two types must be private (in my case, they are mutable pointers to objects in C). These two types are conceptually different, so I put them in different modules ...

pub mod client {
    pub struct Client {
        // private internals
    }
    // Lots of code.
}
pub mod collection {
    pub struct Collection {
        // private internals
    }
    // Lots of code.
}

(In my real case, mod clientthey mod collectionare separate files, i.e., client.rsand collection.rs.)

client.rsneed to create Collection; however, he cannot, since the internal ones are private. Any attempt to write a function has the same problem: the function must be in collection.rs(for access to private members Collection, but it must be pubin order client.rsto access it ... but now it is also pubfor the whole world.

, , - "" . ( pub API, .)

+4
2

Collection (, collection_impl). , Collection. Collection Collection ( ) pub use.

collection_impl , , . , Collection Collection, Collection .

pub mod client {
    use super::collection;
    use super::collection_impl;

    pub struct Client {
        p: i32
    }

    /* this could also be a method on Client */
    pub fn make_collection(client: &Client) -> collection::Collection {
        collection_impl::new_collection(42)
    }
}

mod collection_impl {
    pub struct Collection {
        p: i32
    }

    pub fn new_collection(p: i32) -> Collection {
        Collection { p: p }
    }
}

pub mod collection {
    use super::collection_impl;
    pub use collection_impl::Collection;
}
+3

Rust ++, , Rust :

  • protected
  • friend

, . Rust - , , , .

, :

  • pub fn new Collection
  • , .

; struct, Collection, , , Collection. .

+2

All Articles