How to run Rust in VS Code ?

Rohan Yadav
2 min readSep 16, 2023

--

In MacOS

First, you have to run this command in Terminal, this will install rustup in your system :

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

To Verify installation :

rustc --version
# If 'command not found' then restart the Terminal.

Now, install an extension in your VS Code named `Rust-Analyzer`.

Create a folder and open the folder in VS Code :

After opening the folder in VS Code, tap on the terminal and in the terminal type this :

cargo init

The cargo init command creates a new Cargo project in the current directory. It does this by creating a Cargo.toml file, which is the manifest file for Cargo projects. The Cargo.toml file contains information about the project, such as its name, dependencies, and build instructions.

The cargo init command also creates a src/ directory, where the project's source code will be stored. By default, the cargo init command creates a main.rs file in the src/ directory. This is the entry point for the Rust program.
You can write rust code in the `main.rs`.

To run your code, you can click the run icon(on the top right), but it will not work when you have to take input, because it will run the code in the output section.

So the best method is to run the code in terminal. To do this, navigate to the src folder in the terminal and run this command :

rustc main.rs

This command will compile the code, and to run the code type this command :

./main

When you run the rustc main.rs command it will create a binary file named main and the ./main command will execute the file.

You have to repeat this process every time whenever you make any change in the code.

The main name is by default, you can change this name using this command during creating of the binary file:

rustc main.rs -o <your_choice_name>

To create a new Rust directory, navigate to the folder in the terminal where you want to create the directory and then run this command:

cargo new <new_direcrory_name>

--

--