如何拆分Rust中的模块中的代码? [重复]

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

这个问题在这里已有答案:

我正在阅读Rust Book,我在第7.2章,但我必须遗漏一些东西,因为我无法在模块中组织我的代码,编译器(rustc 1.32.0)一直给我错误。

我读过的

  • 我读了rustc --explain E0433,这是编译器的建议,但我仍然无法解决它。
  • 我检查了Rust by examples,似乎我的代码是正确的,(my/mod.rs在自己的文件夹中使用模块my/nested.rs
  • 我在互联网上找到了一些信息,但它是4年前的,包括使用use,这还没有在书中。
  • 我也检查了this question,但我没有使用文件夹,而且它再次脱离了书的解释。

最小的例子

这是一个试图模仿书中“声音”例子的最小例子,只有两个文件:/src/main.rs/src/m.rs

卖弄.人生

mod m;
fn main() {
  let st_0 = m::St::new();
}

没.人生

pub mod m {
    pub struct St {
        a:i32,
        b:i32,
    }
    impl St {
        pub fn new() -> St{
            println!("New St!");
            St {
                a: 12,
                b: 13,
            }
        }
    }
}

这就是cargo告诉我的:

   Compiling min v0.1.0 (/home/user/min)
error[E0433]: failed to resolve: could not find `St` in `m`
 --> src/main.rs:3:19
  |
3 |     let st_0 = m::St::new();
  |                   ^^ could not find `St` in `m`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0433`.
error: Could not compile `min`.

To learn more, run the command again with --verbose.
module compiler-errors rust
1个回答
1
投票

将所有内容都放在一个文件中时,如下所示:

卖弄.人生

pub mod m {
    pub struct St {
        a:i32,
        b:i32,
    }
    impl St {
        pub fn new() -> St{
            println!("New St!");
            St {
                a: 12,
                b: 13,
            }
        }
    }
}

mod m;
fn main() {
  let st_0 = m::St::new();
}

你用模块包装模块

pub mod mode_name {
    //code...
}

将模块放入另一个文件后,包装就会消失。 The Rust book,显示它,但如果你不仔细看 或者如果你正在编程醉酒 ,您可能会对嵌套模块的pub mod instrument {...}感到困惑。

所以m.rs必须看起来像这样:

pub struct St {
    a:i32,
    b:i32,
}
impl St {
    pub fn new() -> St{
        println!("New St!");
        St {
            a: 12,
            b: 13,
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.