Skip to content
On this page

模块2: exercises/modules/modules2.rs

题目

rust
// modules2.rs
//
// You can bring module paths into scopes and provide new names for them with
// the 'use' and 'as' keywords. Fix these 'use' statements to make the code
// compile.
//
// Execute `rustlings hint modules2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

mod delicious_snacks {
    // TODO: Fix these use statements
    use self::fruits::PEAR as ???
    use self::veggies::CUCUMBER as ???

    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
    );
}

您可以将模块路径引入作用域,并使用useas关键字为其提供别名。修复这些use语句以使代码通过编译。

题目解析

这里主要就是as别名的使用,以及模块内容的可见性。

rust
mod delicious_snacks {
    // TODO: Fix these use statements
    use self::fruits::PEAR as ??? 
    use self::veggies::CUCUMBER as ??? 
    pub use self::fruits::PEAR as fruit; 
    pub 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";
    }
}

参考资料

Powered by VitePress