不能使用“超级”来指代从另一个箱子中“使用”引入的名称

问题描述 投票:1回答:1

我在模块中使用super来引用父命名空间中的名称。但是,当我引用使用use语句引入的父命名空间中的名称时,我无法使其工作。我究竟做错了什么?

// crate mylib

pub fn lib_hello() {println!("Hello from mylib!");}


// crate mybin

extern crate mylib;
use mylib::lib_hello;

fn local_hello() {println!("Hello from here!");}

mod mymod {
    fn f() { super::local_hello() } // Ok
    fn g() { super::lib_hello() }   // error: unresolved name `super::lib_hello`
}

fn main() {
    lib_hello(); // Ok
}

编辑:从local_hello中删除pub

进一步澄清我的要求:函数local_hello()在crate命名空间中声明为private。函数lib_hello()use一起引入,也成为crate命名空间中的私有名称。在这一点上,名称local_hellolib_hello具有相同的地位:它们都在crate命名空间中,并且都是私有的。在mymod中,我使用super来引用crate命名空间,并且可以访问local_hello但不能访问lib_hello。是什么赋予了?

我了解Python和C ++名称空间。也许我需要忘掉一些关键点?

module namespaces rust super
1个回答
4
投票

use语句仅导入到本地范围。如果要重新出口,请使用pub use

// crate mylib

pub fn lib_hello() {println!("Hello from mylib!");}


// crate mybin

extern crate mylib;
pub use mylib::lib_hello;

pub fn local_hello() {println!("Hello from here!");}

mod mymod {
    fn f() { super::local_hello() } // Ok
    fn g() { super::lib_hello() }   // error: unresolved name `super::lib_hello`
}

fn main() {
    lib_hello(); // Ok
}

pub use将使该项似乎存在于重新导出的模块中。

© www.soinside.com 2019 - 2024. All rights reserved.