gpt4 book ai didi

rust - 如何在模块内部使用 const?

转载 作者:行者123 更新时间:2023-11-29 08:24:13 26 4
gpt4 key购买 nike

我有以下代码:

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

我收到一个错误,水果和蔬菜 are private当我尝试打印它们时:

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
| ^^^^^^

谁能解释一下并帮助我解决这个问题?

最佳答案

use 定义的项目的可访问性独立于已使用项目的可访问性。这意味着 PEAR 是公开的,而 use self::fruits::PEAR as fruit; 是私有(private)的。您必须公开导出这些项目:

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

( Permalink to the playground )

关于rust - 如何在模块内部使用 const?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58043900/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com