[Solved] Can I access a private method from one module but not allow it in a public API?

Here is some code that doesn't compile (code in playground):

use B::Y;

fn main() {
    let y = Y::new(7);
    let z = y.get();
    println!("{:?} {}", y, z);
}

pub mod A {
    #[derive(Debug)]
    pub struct X { pub i: i32, }
    impl X {
        pub fn new(i: i32) -> X { X{i} }
        fn private(&self) -> i32 { self.i * self.i }
    }
}

pub mod B {
    use crate::A::X;
    #[derive(Debug)]
    pub struct Y {
        pub j: i32,
        k: X,
    }
    impl Y {
        pub fn new(j: i32) -> Y { Y{j, k: X::new(j*2)} }
        pub fn get(&self) -> i32 { self.k.private() }
    }
}

I don't want the A::X::private() method to be in the X type's public API; but I do want to use it from another module. Can this be done in rust? Could I make private() public but then restrict it so it isn't in the public API but is usable from another module? (In reality main(), mod A, and mod B will all be in separate files if that makes a difference).

Rationale: I want to create various modules that interact with each other --- so need to be able to call each other's methods --- but offer a much more contrained API to users of the library which is built from these modules.

pub(crate) or pub(super) might be what you want.

1 Like

Could you edit the rust playground code or just quote the actual changes since I don't understand.

Ah, I get it now, instead of pub fn foo(), I use pub(crate) fn foo() or pub(in crate::bar) foo() etc.

Thanks.

This topic was automatically closed after 32 hours. New replies are no longer allowed.