How does the import/module system in Rust work?

匿名 (未验证) 提交于 2019-12-03 01:34:02

问题:

I'm currently learning Rust. I've just mastered the borrowing system, but I don't know how the module system works.

To import an extern module, I must write extern crate sdl2;. But what if I want to import a non extern crate?

I know I can define a module using mod like:

mod foo {     fn bar(length: i32) -> Vec<i32> {         let mut list = vec![];         for i in 0..length + 1 {             if list.len() > 1 {                 list.push(&list[-1] + &list[-2]);             } else {                 list.push(1);             }         }         list     } }

And use it in the same file with foo::, but how can I use functions/modules from other files?

Just for sake of details imagine this setup:

. |-- Cargo.lock |-- Cargo.toml `-- src     |-- foo.rs     `-- main.rs

So in src/foo.rs I have:

fn bar(length: i32) -> Vec<i32> {     let mut list = vec![];     for i in 0..length + 1 {         if list.len() > 1 {             list.push(&list[-1] + &list[-2]);         } else {             list.push(1);         }     }     list }

And I want to use it in src/main.rs. When I try a plain use foo::bar, I get:

  | 1 | use foo::bar;   |     ^^^^^^^^ Maybe a missing `extern crate foo;`?

When putting the function inside mod foo {...} I get the same error.

If there is any post about this topic, give me a link to it as I get nothing but the Rust Book.

回答1:

Add this declaration to your main.rs file:

mod foo;

Which acts like a shorthand for:

mod foo { include!("foo.rs") }

Though it knows that if there isn't a foo.rs file, but there is a foo/mod.rs file, to include that instead.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!