Setting up VSC for Rust

OK, I'm totally new to Rust. I'm evaluating Rust for a coming project, and I've run simple test programs.
I'm stuck on the simplest question ever. I use VSC. I'm adding source files to the src folder, but they won't get included in my build. If main.rs calls a function in function.rs, I'll the following get build error:

 --> src\main.rs:3:5
  |
3 |     function( 1 );
  |     ^^^^^^^^ not found in this scope

Believe it or not, but the trick to adding source files to a project is nowhere described!

It is described here
https://doc.rust-lang.org/book/ch07-00-managing-growing-projects-with-packages-crates-and-modules.html
I recommend to read the whole book.

Tldr:

Every module must be declared before it can be used.
It can be inline in main.rs

mod function {

    fn function() {
        todo!();
    }
}

or as a file src/function.rs and then in main.rs

mod function;

or a whole folder. Read the link to see how to do that.

The function can then be called anywhere in the project by using it's path. In this case either

crate::function::function();

or

use crate::function;

function::function();

Btw, the title of you post seems a bit misleading. What does adding source files to the project have to do with adding source files to the version control system?

EDIT

Sorry I misread😂 I guess VSC is visual studio code?

Maybe not: the title did say "VCS"; I changed it to "VSC" to match the post body because this did seem to be about an IDE (I too guess VSC is Visual Studio Code) and not a version control system.

1 Like

if you want to just include another rust code file, like you would in C, you can use the include! macro.

// foo.rs
fn foo() {
  println!("foo");
}

// main.rs
include!("foo.rs"); // this literally inserts the contents of foo.rs at this point

fn main() {
  foo();
}

but you can use a mod declaration, which is better.

// foo.rs, same as before
fn foo() {
  println!("foo");
}

// main.rs
mod foo; // we declare the module foo, only main.rs, lib.rs and mod.rs files can declare modules

fn main() {
  foo::foo() // we need to use `foo::` here, because the contents of foo.rs are scoped under the module
}

But what you should be doing is using cargo (which it looks like you aren't).
it manages dependencies, versioning, publishing and a bunch of other stuff.

@SebastianJL: Thank you. I've followed your advice and read the book, and this problem is solved.

1 Like

@SebastianJL: VSC means Visual Studio Code, indeed. The title is misleading because VSC has nothing to do with this, only the code. But I didn't know that when I posted the question.

@jvcmarcenes: Thank you. I've used mod, and it works perfectly. I do use cargo, but cargo didn't help me solve this problem.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.