[英]Rust importing .rs fails
我的src/
文件夾中有三個文件: main.rs
, lib.rs
和cfgtools.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和這種導入概念並不陌生。
這里的問題是包裝箱和模塊之間有些混淆。 您的所有源文件都是同一包裝箱中的模塊。 聽起來好像lib.rs
,而您只需要cfgtools
模塊。 extern crate
用於導入其他單獨存放的庫; 還需要在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!");
}
我將這些文件放在cargo init --bin .
之后的src/
cargo init --bin .
創建一個新的空白板條箱,然后cargo run
打印出該消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.