Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use const inside modules?

Tags:

rust

I have the following code:

mod delicious_snacks {
    use self::fruits::PEAR as fruit;
    use self::veggies::CUCUMBER as veggie;

    mod fruits {
        pub const PEAR: &'static str = "Pear";
        pub const APPLE: &'static str = "Apple";
    }

    mod veggies {
        pub const CUCUMBER: &'static str = "Cucumber";
        pub const CARROT: &'static str = "Carrot";
    }
}

fn main() {
    println!(
        "favorite snacks: {} and {}",
            delicious_snacks::fruit,
            delicious_snacks::veggie
    );
}

I'm getting an error that fruit and veggie are private when I try to print them:

error[E0603]: constant `fruit` is private
  --> src/main.rs:19:31
   |
19 |             delicious_snacks::fruit,
   |                               ^^^^^

error[E0603]: constant `veggie` is private
  --> src/main.rs:20:31
   |
20 |             delicious_snacks::veggie
   |                               ^^^^^^

Can any one explain me this and help me resolve?

like image 517
iamsaquib8 Avatar asked Dec 31 '22 15:12

iamsaquib8


1 Answers

The accessibility of an item defined with use is independent from the accessibility of the used item. This means that while PEAR is public, use self::fruits::PEAR as fruit; is private. You must export those items publicly:

pub use self::fruits::PEAR as fruit;
pub use self::veggies::CUCUMBER as veggie;

(Permalink to the playground)

like image 58
mcarton Avatar answered Jan 05 '23 18:01

mcarton