Rust导入.rs失败

时间:2017-01-08 12:26:59

标签: import rust

我的src/文件夹中有三个文件:main.rslib.rscfgtools.rs。我想导入cfgtools.rs

main.rs

extern crate cfgtools;

use cfgtools::*;

fn main() {
    let os = get_os();
    println!("Your OS: {}",os);
}

lib.rs

pub mod cfgtools;

cfgtools.rs

pub fn get_os() -> &'static str {
        let mut sys:&'static str = "unknown";
        if cfg!(target_os = "windows")   { sys = "windows" };
        if cfg!(target_os = "macos")     { sys = "macos" };
        if cfg!(target_os = "ios")       { sys = "ios" };
        if cfg!(target_os = "linux")     { sys = "linux" };
        if cfg!(target_os = "android")   { sys = "android" };
        if cfg!(target_os = "freebsd")   { sys = "freebsd" };
        if cfg!(target_os = "dragonfly") { sys = "dragonfly" };
        if cfg!(target_os = "bitrig")    { sys = "bitrig" };
        if cfg!(target_os = "openbsd")   { sys = "openbsd" };
        if cfg!(target_os = "netbsd")    { sys = "netbsd" };
        return sys;
}

但是,我收到了一个错误:

   Compiling sys_recog v0.1.0 (file:///home/sessho/rust/sys_recog)
error[E0463]: can't find crate for `cfgtools`
  --> main.rs:17:1
   |
17 | extern crate cfgtools;
   | ^^^^^^^^^^^^^^^^^^^^^^ can't find crate

我是Rust的新手,也是这个导入的概念。

1 个答案:

答案 0 :(得分:4)

这里的问题是板条箱和模块之间的混淆。您的所有源文件都是同一个包中的模块。听起来不需要lib.rs,你只需要一个cfgtools模块。 extern crate用于导入单独保存的其他库; extern crates也需要在Cargo.toml中声明,以便Cargo可以找到它们。

所以它应该是这样的:

main.rs

// Declare the module, which will be there as cfgtools.rs in the same directory.
mod cfgtools;

// Make things in cfgtools visible.  Note that wildcard imports
// aren't recommended as they can make it confusing to find where
// things actually come from.
use cfgtools::foo;

// and use it:
fn main() {
    foo();
}

cfgtools.rs

// Note pub to make it visible outside the module
pub fn foo() {
    println!("Hello, world!");
}

我在src/之后将这些文件放在cargo init --bin .中以创建新的空白包,并cargo run打印出该消息。